proxy监听对象变化
遍历普通对象
let person = { age: 0, school: '大学', } let hander = { get(obj, key) { return key in obj ? obj[key] : 66 }, set(obj, key, val) { console.log('key', key) obj[key] = val return true } } let proxyObj = new Proxy(person, hander) proxyObj.age // 0 proxyObj.test // 66 proxyObj.age = 30 // key age 30
深度遍历
Proxy和defineProperty的一个共同特性,不支持对象嵌套。需要递归去实现
let person = { age: 0, school: '大学', children: { name: '小明' } } let hander = { get(obj, key) { return key in obj ? obj[key] : 66 }, set(obj, key, val) { console.log('key', key) obj[key] = val return true } } let deepProxy = function(obj) { if (typeof obj === 'object') { Object.entries(obj).forEach(([key, value]) => { obj[key] = deepProxy(value); }) return new Proxy(obj, hander) } return obj; } let proxyObj = deepProxy(person) proxyObj.age //0 proxyObj.test // 66 proxyObj.age = 30 // key age 30 proxyObj.children.name = '小华' // key name '小华'