2017-07-06 326 views
0

我該如何在JavaScript中做這樣的事情?從屬javascript對象屬性

obj = { 
    prop1 = 0; 
    prop2 = 0; 
    prop3 = prop1 + prop2; 
} 

因此,當obj.prop1被更新時,obj.prop3會自動更新。

+0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects# Defining_getters_and_setters – Bergi

回答

7

儘量讓prop3的getter/setter,見例如

var obj = { 
 
    prop1: 1, 
 
    prop2: 4, 
 
    get prop3() { 
 
     return this.prop1 + this.prop2; 
 
    } 
 
}; 
 

 
console.log(obj.prop3); 
 
obj.prop1 = 6; 
 
console.log(obj.prop3);