Node.js,观察类字段的变化

时间:2018-07-18 22:20:40

标签: javascript node.js proxy

是否可以为nodejs中的类属性创建直接代理监视程序?

class User{
    constructor(name){
        this.name = name;
        let pObject = new Proxy(this,{
            set: () => {
                console.log("something changed"); // should be called
                return true;
            }
        })
        Object.assign(this, pObject) // something like this?
    }
}



let user = new User("Mike");
user.name = "Jack"

2 个答案:

答案 0 :(得分:2)

您是否只想观察实例上的二传手?您可以返回代理本身:

class User {
  constructor(name) {
    this.name = name;
    let pObject = new Proxy(this, {
      set: (obj, prop, value) => {
        console.log("something changed"); // should be called
        return Reflect.set(obj, prop,value)      // set the property
      }
    })
    return pObject
  }
}



let user = new User("Mike");
user.name = "Jack"
user.state = "Alaska"
console.log(user)
console.log(user instanceof User)

答案 1 :(得分:1)

Mark Meyer已经回答了,这是我的看法(我迟到了几分钟才发布了此内容):

class User {
    constructor(name) {
        this.name = name;
        this.UserProxy = {
            set(object, prop, value) {
                console.log('Object ', object);
                console.log('Prop ', prop);
                console.log('Value ', value);
                // Do whatever you wish to 
            }
        };
        return new Proxy(this, this.UserProxy);
    }
}

let user = new User('Mike');
user.name = 'Jack';
user.name = 'Falcon';