let obj = { a: 111 } // 递归给对象的属性劫持set方法 function watch(obj, fn) { Object.keys(obj).forEach(key => { Object.defineProperty(obj, key, { enumerable: true, configurable: true, set(newVal) { fn(key, newVal) } }) }) } // 使用 watch(obj, (prop, newVal) => console.log(prop, newVal)) obj.a = 777 console.log(obj)
已解决
悬赏分:50
- 解决时间 2021-11-26 23:31
点赞 0反对 0举报 0
收藏 0
分享 0
回答2
最佳
-
你没有设置get
function watch(obj, fn) { Object.keys(obj).forEach(key => { var value = obj[key]; Object.defineProperty(obj, key, { enumerable: true, configurable: true, get() { return value; }, set(newVal) { fn(key, newVal) } }) }) }
支持 0 反对 0 举报2021-11-26 08:08