[Javascript] Using Proxy to observe the object

const obj = {
  a: 1,
  b: 2,
  c: {
    d: 1,
    e: 2,
  },
};

function isObject(val) {
  return val !== null && typeof val === "object";
}

function observe(obj) {
  const proxy = new Proxy(obj, {
    get(target, key) {
      const val = Reflect.get(target, key);
      console.log(key, "get", val);
      if (isObject(val)) {
        return observe(val);
      }
      return val;
    },
    set(target, key, newVal) {
      const oldVal = target[key];
      if (isObject(oldVal)) {
        observe(oldVal);
      }
      console.log(key, "set", newVal);
      return Reflect.set(target, key, newVal);
    },
    deleteProperty(target, key) {
      console.log(key, "delete");
      return Reflect.deleteProperty(target, key);
    },
  });
  return proxy;
}

const pobj = observe(obj);
pobj.a;
pobj.a = 3;
pobj.c.d;
pobj.c.d = 3;

delete pobj.b;

pobj.f = 123;

/*
a get 1
a set 3
c get { d: 1, e: 2 }
d get 1
c get { d: 1, e: 2 }
d set 3
b delete
f set 123
*/

 

Refer to previous blog for defineProperty.

Compare with definePropertyvs Proxy, we can clearly see that Proxy is more flexible and better perforemance.

For defineProperty, we have to deep loop over the object props, but Proxy we don't need to.

And proxy can observe not only existing props, but also for new props and delete props.

posted @   Zhentiw  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-10-09 [Typescript] Tips: Throw detailed error messages for type checks
2022-10-09 [RxJS] Ignore values during windows using throttleTime
2022-10-09 [Algorithm] DP - Min Number of Jumps
2020-10-09 [Typescript] Emitting Declaration Files
2020-10-09 [Typescript] Augmenting Modules with Declarations
2018-10-09 [Angular] Write Compound Components with Angular’s ContentChild
2016-10-09 [TypeScript] Distinguishing between types of Strings in TypeScript
点击右上角即可分享
微信分享提示