[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 defineProperty
vs 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.