- 使用 Object.defineProperty()
function observe(obj) {
for (let key in obj) {
let val = obj[key];
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function () {
return val;
},
set: function (newVal) {
if (newVal !== val) {
console.log(`属性 ${key} 从 ${val} 变成了 ${newVal}`);
val = newVal;
}
}
});
}
}
let obj = { count: 0 };
observe(obj);
obj.count = 1;
function observe(obj) {
return new Proxy(obj, {
get(target, propKey, receiver) {
return Reflect.get(target, propKey, receiver);
},
set(target, propKey, value, receiver) {
let oldValue = target[propKey];
if (value !== oldValue) {
console.log(`属性 ${propKey} 从 ${oldValue} 变成了 ${value}`);
}
return Reflect.set(target, propKey, value, receiver);
}
});
}
let obj = { name: 'zs', age: 20, gender: 'male' };
obj = observe(obj);
obj.age = 1;
网友评论