[Javascript] Using defineProperty to observe the object props changes
const obj = {
a: 1,
b: 2,
c: {
a: 1,
b: 2,
},
};
function isObject(val) {
return val !== null && typeof val === "object";
}
function observe(obj) {
for (let key in obj) {
let v = obj[key];
if (isObject(v)) {
observe(v);
}
Object.defineProperty(obj, key, {
get() {
console.log(key, "read", v);
return v;
},
set(val) {
if (val !== v) {
console.log(key, "set", val);
v = val;
}
},
});
}
}
observe(obj);
obj.a;
obj.a = 3;
obj.c.a;
obj.c.b = 3;
console.log(JSON.stringify(obj));
/*
a read 1
a set 3
c read { d: [Getter/Setter], e: [Getter/Setter] }
d read 1
c read { d: [Getter/Setter], e: [Getter/Setter] }
e set 3
a read 3
b read 2
c read { d: [Getter/Setter], e: [Getter/Setter] }
d read 1
e read 3
{"a":3,"b":2,"c":{"d":1,"e":3}}
*/
Using defineProperty can only observe the existing props, if we add a new prop, then we are not able to observe it anymore
observe(obj);
obj.f = 123; // not albe to observe the changes, due to observe function has been called with existing properties
Also we are not able to observe deleted prop:
observe(obj);
delete obj.b;
So defineProperty is limited only to existing props of the object.
If we want to achieve better result, we have to use Proxy
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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