You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Object/Function/Class中改写Getter和Setter实现LocalStorage映射?

实现动态键名的localStorage缓存对象

你想要的是一个能自动拦截所有属性读写、并映射到带前缀的localStorage项的对象,用ES6的Proxy就能完美实现,代码如下:

const cache = new Proxy({}, {
  set(target, key, value) {
    localStorage.setItem(`prefix_${key}`, value);
    return true; // 返回true表示属性设置成功
  },
  get(target, key) {
    return localStorage.getItem(`prefix_${key}`);
  }
});

代码说明

  • Proxy会拦截cache对象上的所有属性操作,不管是已定义还是新增的键名
  • 当你执行cache.a = 'someVal'时,set方法自动触发,把键名加上prefix_前缀后存入localStorage
  • 当你读取cache.a时,get方法触发,自动读取对应前缀的localStorage项并返回

验证效果

执行你期望的代码:

// 赋值
cache.a = 'someVal';
// 此时localStorage已自动执行 setItem('prefix_a', 'someVal')

// 读取
console.log(cache.a);
// 自动执行 getItem('prefix_a') 并输出 'someVal'

扩展:支持非字符串类型存储

如果需要存储对象、数组等非字符串数据,可以在存储时序列化,读取时反序列化:

const cache = new Proxy({}, {
  set(target, key, value) {
    localStorage.setItem(`prefix_${key}`, JSON.stringify(value));
    return true;
  },
  get(target, key) {
    const rawData = localStorage.getItem(`prefix_${key}`);
    return rawData ? JSON.parse(rawData) : rawData;
  }
});

内容的提问来源于stack exchange,提问作者Xavier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:30:55