xvno / blog

个人博客, 不定期发布技术笔记和个人随笔.
0 stars 0 forks source link

ES: Reflect & Proxy #118

Open xvno opened 3 years ago

xvno commented 3 years ago

[Refs]

xvno commented 3 years ago

Reflect

静态方法

xvno commented 3 years ago

Proxy

静态方法:

Proxy 实例的方法

xvno commented 3 years ago

使用 Proxy 实现观察者模式


function observe(obj) {
    let preCallbackSet = new Set();
    let sufCallbackSet = new Set();

    let proxy =  new Proxy(obj, {
        set (obj, key, value, receiver) {
            preCallbackSet.forEach(cb => {
                cb(obj, key, value);
            });
            Reflect.set(obj, key, value, receiver);
            sufCallbackSet.forEach(cb => {
                cb(obj, key, value);
            });
        }
    })

    proxy.subPre = function(fn) {
        preCallbackSet.add(fn);
    }
    proxy.subSuf = function(fn) {
        sufCallbackSet.add(fn);
    }

    return proxy;
}

let o = {name: 'o'};
let po = observe(o);

o.subPre(function(obj, k, v) {
    console.log('Changing...');
});

o.subPre(function(obj, k, v) {
    console.log(obj, k, v);
});

o.subSuf(function(obj, k, v) {
    console.log(obj, k, v);
});

o.subSuf(function(obj, k, v) {
    console.log('Changed!!!');
});

po.age = 11;
po.age = 12;
xvno commented 3 years ago

preventExtensions & isExtensible


function observe(obj) {
    let preCallbackSet = new Set();
    let sufCallbackSet = new Set();
    let prevented = !Reflect.isExtensible(obj);
    console.log(prevented, '...')
    let proxy =  new Proxy(obj, {
        set (obj, key, value, receiver) {
            preCallbackSet.forEach(cb => {
                cb(obj, key, value);
            });

            Reflect.set(obj, key, value, receiver);
            sufCallbackSet.forEach(cb => {
                cb(obj, key, value);
            });
        },
        get(obj, key) {
            if(key === 'isPrevented') {
                return prevented;
            } else {
                return Reflect.get(obj, key);
            }

        }
    })

    proxy.subPre = function(fn) {
        preCallbackSet.add(fn);
    }
    proxy.subSuf = function(fn) {
        sufCallbackSet.add(fn);
    }
    proxy.preventExtensions = function() {
        prevented = true;
        Reflect.preventExtensions(obj)
    }

    return proxy;
}

let o = {name: 'o'};
let po = observe(o);

o.subPre(function(obj, k, v) {
    console.log('Changing...');
});

o.subPre(function(obj, k, v) {
    console.log(obj, k, v);
});

o.subSuf(function(obj, k, v) {
    console.log(obj, k, v);
});

o.subSuf(function(obj, k, v) {
    console.log('Changed!!!');
});

po.age = 11;
po.age = 12;

console.log(!Reflect.isExtensible(o))
console.log(po.isPrevented)
po.preventExtensions();
console.log(!Reflect.isExtensible(o))
console.log(po.isPrevented)