1.Object.defineProperty
使用:
// 本体
const obj1 = {a: 1,b: 2,c: 3,
};// 通过代理对象 来监听本体修改
const definePropertyObj = {};
// 使用Object.defineProperty监听对象
for (const key in obj1) {Object.defineProperty(definePropertyObj, key, {get() {console.log("get", key);return obj1[key];},set(value) {console.log("set", key, value);obj1[key] = value;},});
}// 获取
definePropertyObj.a
// 修改
definePropertyObj.a = 100
2.Proxy
使用:
// 本体
const obj1 = {a: 1,b: 2,c: 3,
};const proxyObj = new Proxy(obj1,{get(target, key) {console.log("target -->>", target);console.log("key -->>", key);return target[key];},set(target, key, value) {console.log("target -->>", target);console.log("key -->>", key);console.log("value -->>", value);target[key] = value;},}
);
// 获取
obj1.a
// 修改
obj1.a = 100