gaowei1012 / blog

this is blog
2 stars 0 forks source link

使用JavaScript闭包试下缓存数据 #71

Open gaowei1012 opened 3 years ago

gaowei1012 commented 3 years ago

使用闭包实现缓存


/**
 * 闭包实现缓存
 * 属性: key -value 将数据缓存在一个对象中
 * 通过setCache进行设置缓存,getCache 读取缓存
 * @returns
 */
const configCache = function() {
  const _cache = new Map()
  return {
    setCache (k, v) {
      _cache[k] = v
      return this
    },
    getCache (k) {
      return _cache[k]
    },
    removeCache(k) {
      delete _cache(k)
      return this
    }
  }
}

const newConfigCache =  configCache()
newConfigCache.setCache('app_id', 'hello app')
console.log('newConfigCache=====>>>', newConfigCache.getCache('app_id'))

输出 image