proxy 实现一个数据绑定和监听

let onWatch(obj, setBind, getLogger) => {
    let handler = {
        get(target, property, receiver) {
            getLogger(target, property);
        },
        set(target, property, value, receiver) {
            setBind(value);
            return Reflect.set(target, property, value);
        }
    };
    return new Proxy(obj, handler);
};

let obj = { a: 2};
let vlaue;
let result = onWatch(obj, (val) => {
    value = val;
}, (target, property) => {
    console.log(`Get '${property}' = ${target[property]}`);
})
result.a = 2
console.log('result.a:', result.a);

 

posted @ 2019-10-25 17:49  单先生  阅读(423)  评论(0编辑  收藏  举报