**方法一:**set 屬性名稱(參數){}
var wallet = {
total: 100,
set save(input) { //Setter, input為參數
this.total = this.total + input / 2;
},
};
wallet.save = 300;
console.log(wallet.total); //100+300/2
**方法二:**利用Object.defineProperty
var wallet = {
total: 100,
};
Object.defineProperty(wallet, 'save', { //新增save屬性,並操作該屬性
set: function (input) { //input為參數
this.total = this.total + input / 2;
},
});
wallet.save = 300;
console.log(wallet.total); //250
**方法一:**get 參數名稱(){}
var wallet = {
total: 100,
set save(input) {
this.total = this.total + input / 2;
},
get output() { //Getter為取值,無須傳入參數
return this.total / 2;
},
};
wallet.save = 300;
console.log(wallet.output); //125
在chrome瀏覽器上用滑鼠點{...},才會出現Getter運算完畢的值
方法二:
var wallet = {
total: 100,
};
Object.defineProperty(wallet, 'save', {
get: function () {
return this.total / 2
},
});
console.log(wallet); //50
用 Object.defineProperty
建立Getter,在chrome瀏覽器會出現save屬性的顏色跟total屬性顏色不同
用 console.log(Object.getOwnPropertyDescriptor(wallet, 'save'));
檢查該屬性的特徵。
修改後,
var wallet = {
total: 100,
};
Object.defineProperty(wallet, 'save', {
configurable: true, //由false變更為true
enumerable: true, //由false變更為true
get: function () {
return this.total / 2
},
});
console.log(wallet); //50