const object2 = {
name: "张三",
age: 20,
};
function observable(object) {
return new Proxy(object, {
get(object, key) {
console.log(`你访问了${key}`);
return Reflect.get(object, key);
},
set(object, key, value) {
const result = Reflect.set(object, key, value);
for (const observer of queuedObservers) {
observer();
}
return result;
},
});
}
const person = observable(object2);
const queuedObservers = new Set();
const observe = (callback) => {
queuedObservers.add(callback);
};
function print() {
console.log(`${person.name}今年${person.age}岁`);
}
observe(print);
person.age= 400