https://mp.weixin.qq.com/s/r55lQeLqqwkDk89z4oX6oQ
监听一个对象属性的变化
a = "123456"; data = a; Object.defineProperty(window, "a", { get() { console.log("取值a的值: ", data); return data }, set(v) { data = v; console.log("a重新赋值: ", v); return v } }); a = "123";
监听一个对象多个属性的变化
function copyObj(obj) { return JSON.parse(JSON.stringify(obj)) } var params = { "signature": "123456", "sign": "abcd" }; var p1 = copyObj(params); Object.defineProperties(params, { "signature": { get() { console.log("获取了signature值: ", p1.signature); return p1. signature }, set(v) { p1. signature = v; console.log("signature重新赋值: ", v); return v } }, "sign": { get() { console.log("获取了sign值: ", p1.sign); return p1. sign }, set(v) { p1. sign = v; console.log("sign重新赋值: ", v); return v } } }); params.signature = "12345"; params.sign = "qwer";
监听整个对象属性的变化
var params = { "signature": "123456", "sign": "abcd" }; params = new Proxy(params, { get: function(target, key, receiver) { console.log(`获取了key:${key},值:${target[key]}`); return target[key] }, set: function(target, key, value, receiver) { target[key] = value; console.log(`修改了key:${key},新值:${value}`); return true } }); params.signature = "1234"; console.log(params.signature);