我需要检查对象的元素是否已更改并根据它更改另一个值。
例如:
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)
最佳答案
使 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)
关于javascript - 检查某个类的对象的值是否已被更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63148415/