1. 程式人生 > >es6觀察者模式實現

es6觀察者模式實現

//es6實現 藉助set實現


function obfunction(oldval,newval){
console.log(oldval+'變成了'+newval);
}
class targetObser{
constructor(age,name){
this.age=age;
this.name=name;
}
set name(val){
console.log(name)
obfunction(name,val)
name=val;
}
}

//藉助proxy reflect實現

class TargetObj {

    constructor(age, name) {
        this.name = name;
        this.age = age;
    }
}
let targetObj = new TargetObj(1, 'Martin');
let observerProxy = new Proxy(targetObj, {
    set(target, property, value, reciever) {
        if (property === 'name') {
            observer(target[property], value);
        }
        Reflect.set(target, property, value, reciever);
    }
}); // 定義值改變時的處理函式
function observer(oldVal, newVal) {    // 其他處理邏輯...    
console.info(`name屬性的值從 ${oldVal} 改變為 ${newVal}`);
}
observerProxy.name = 'Lucas';
console.info(targetObj);