好好学习,认真工作

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  '小华'

 

posted on 2022-05-13 11:26  peace_1  阅读(246)  评论(0编辑  收藏  举报