es6观察者模式

Others 2022-11-02 06:34:45 2022-11-02 06:34:45 890 次浏览
// 被观察的目标对象
let obj = { name: 'zyc', csdn: '博客'};
// 观察者
function print() {
    console.log('对象被操作了!');
}
// 使用proxy代理
const observeObj = (obj) => new Proxy(obj, {set, get});
// 消息队列
const observeQueue = new Set();
const observe = (fn) => observeQueue.add(fn);
 
// 设置
function set(target, key, value, receiver) {
    let result = Reflect.set(target, key, value, receiver);
    for(let item of observeQueue) {
        item.call(this);
    }
    return result;
}
// 获取
function get(target, key, receiver) {
    let result = Reflect.get(target, key, receiver);
    for (let item of observeQueue) {
        item.call(this);
    }
    return result;
}
 
// 代理对象
let proxy= observeObj(obj);
// 推入消息队列中
observe(print);
 
// 触发测试
proxy.name = "张三";
console.log(proxy.name);