用闭包封装本地缓存工具,核心是利用函数作用域隔离数据并模拟命名空间:私有store对象隐藏于iife内,通过set/get/remove/clear等api操作;支持命名空间分层、json序列化及ttl过期控制。

用闭包封装本地缓存工具,核心是利用函数作用域隔离数据,再通过对象属性模拟命名空间,避免全局污染和键名冲突。
用闭包隐藏缓存数据
把缓存容器(如 plain object)定义在立即执行函数内部,外部无法直接访问,只能通过返回的 API 操作:
const createCache = () => {
const store = {}; // 私有缓存对象,外部不可见
return {
set(key, value) { store[key] = value; },
get(key) { return store[key]; },
remove(key) { delete store[key]; }
};
};
const cache = createCache(); // 每次调用都生成独立作用域
支持命名空间的结构设计
在私有 store 上按命名空间分层,比如用 namespace.key 作键,或用嵌套对象:
推荐后者——更清晰、可遍历、易清理整个命名空间:
- store[ns] = {} 存每个命名空间的键值对
- set(ns, key, value) → store[ns][key] = value
- get(ns, key) → store[ns]?.[key]
- clear(ns) → delete store[ns] 或 store[ns] = {}
增强实用性:自动序列化与过期控制
localStorage 只支持字符串,需 JSON 序列化;加上时间戳实现简易 TTL:
- 写入时存
{ value, expires: Date.now() + ttl } - 读取时先检查
expires是否过期,过期则自动删除并返回 undefined - ttl 单位毫秒,0 或 undefined 表示永不过期
完整轻量实现示例
const createNamespaceCache = () => {
const store = {};
const getNs = (ns) => {
if (!store[ns]) store[ns] = {};
return store[ns];
};
return {
set(ns, key, value, ttl = 0) {
const nsStore = getNs(ns);
const item = { value };
if (ttl > 0) item.expires = Date.now() + ttl;
nsStore[key] = item;
},
get(ns, key) {
const nsStore = getNs(ns);
const item = nsStore[key];
if (!item) return undefined;
if (item.expires && Date.now() > item.expires) {
delete nsStore[key];
return undefined;
}
return item.value;
},
remove(ns, key) {
const nsStore = getNs(ns);
delete nsStore[key];
},
clear(ns) {
if (ns) delete store[ns];
else Object.keys(store).forEach(k => delete store[k]);
}
};
};
// 使用
const cache = createNamespaceCache();
cache.set('user', 'profile', { name: 'Alice' }, 60000); // 1分钟过期
console.log(cache.get('user', 'profile')); // { name: 'Alice' }
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











