【问题标题】:Check if a value of an object of certain class has been altered检查某个类的对象的值是否已被更改
【发布时间】:2020-11-18 17:42:04
【问题描述】:

我需要检查一个对象的元素是否已被更改并根据它更改另一个值。

例如:

class myClass{
  constructor(value1, value2){
    this.value1 = value1
    this.value2 = value2
    this.values = {
      value1: this.value1,
      value2: this.value2
    }
  }
}

var myObject = new myClass(2,4)
console.log(myObject.value1, myObject.values)

myObject.value1++ // ou myObject.value1 = 3
//expected log 3 {"value1": 3, "value2": 4}
console.log(myObject.value1, myObject.values)

【问题讨论】:

    标签: javascript html css node.js


    【解决方案1】:

    如果你想动态处理一个对象的所有属性,那么你可以使用 Proxy 而不是分开的 setter 和 getter。

    class myClass{
      constructor(value1, value2){
        this.value1 = value1
        this.value2 = value2
        this.values = {
          value1: this.value1,
          value2: this.value2
        }
      }
    }
    
    var myObject = new myClass(2,4);
    
    var proxied = new Proxy(myObject, {
      get(target, prop) {
        return Reflect.get(prop === "values" ? target : target.values, prop);
      },
      set(target, prop, value) {
        return Reflect.set(prop === "values" ? target : target.values, prop, value);
      }
    });
    
    proxied.value1++ // ou myObject.value1 = 3
    proxied.value2 = 1000;
    console.log("proxy", proxied);

    【讨论】:

      【解决方案2】:

      使myClass 实例成为单一事实来源。

      class myClass{
        constructor(value1, value2){
          this.value1 = value1
          this.value2 = value2
          const container = this;
          
          this.values = {
            get value1() {
              return container.value1
            },
            get value2() {
              return container.value2
            }
          }
        }
      }
      
      var myObject = new myClass(2,4)
      console.log(myObject.value1, myObject.values)
      
      myObject.value1++ // ou myObject.value1 = 3
      //expected log 3 {"value1": 3, "value2": 4}
      console.log(myObject.value1, myObject.values)

      【讨论】:

      • 哦,我刚刚尝试使用get value1(){return this.value1},我没有想过使用一个变量作为this。它是如此简单。谢谢!
      • @LuísHNrique this 在 getter 中将是 values 对象,因此调用 this.value1 基本上会导致 StackOverflow :)
      猜你喜欢
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 2011-10-10
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多