Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

通过 proxy 代理 Map 结构 #115

Open
Genluo opened this issue May 8, 2023 · 0 comments
Open

通过 proxy 代理 Map 结构 #115

Genluo opened this issue May 8, 2023 · 0 comments

Comments

@Genluo
Copy link
Owner

Genluo commented May 8, 2023

// 存储代理对象和原始对象的映射
const proxyToRaw = new WeakMap();

// 自定义的拦截器,在这里对调用的Map方法进行拦截
const interceptors = {
  get(key) {
    // 通过代理对象获取原始对象 (proxy => map)
    const rawTarget = proxyToRaw.get(this);
    return rawTarget.get(key);
  },
  set(key, value) {
    const rawTarget = proxyToRaw.get(this);
    return rawTarget.set(key, value);
  },
};

// 创建Proxy对象,同时将代理对象和原始对象建立一个映射
const createProxy = (obj) => {
  const proxy = new Proxy(obj, {
    get(target, key, receiver) {
      // 如果调用的key存在于我们自定义的拦截器里,就用我们的拦截器
      target = interceptors.hasOwnProperty(key) ? interceptors : target;
      return Reflect.get(target, key, receiver);
    },
  });
  // 让proxy后的对象指向原始对象
  proxyToRaw.set(proxy, obj);
  return proxy;
};

const map = createProxy(new Map());

map.set("key", "value");
map.get("key"); // 输出value

作者:ZHANGYU
链接:https://juejin.cn/post/6884473952060571661
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 注意 WeakMap 的使用
  • 注意 Reflect 的相关操作
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant