Setter 與 Setter
Getter: 取得特定值的方法
Setter: 存值的方法
Getter
var wallet = {
total: 100,
set save(price){
this.total = this.total + price / 2
}
}
wallet.save = 300;
console.log(wallet.total); // 250
Getter + Setter
var wallet = {
total: 100,
set save(price){
this.total = this.total + price / 2
},
get save(){
return this.total / 2;
}
}
wallet.save = 300;
console.log(wallet.save); // 125
另一種定義方式(Object.defineProperty)
但要注意
如果用 defineProperty 去定義getter , setter
則 enumerable , configurable 預設為false
var wallet = {
total: 100,
}
Object.defineProperty(wallet,'save',{
configurable: true,
enumerable: true,
set : function(price){
this.total = this.total + price / 2;
},
get : function(){
return this.total / 2;
}
})
wallet.save = 300;
console.log(wallet);
這裡在舉一個例子
var a = [1,2,3];
Object.defineProperty(Array.prototype,'latest',{
get: function(){
return this[this.length - 1]
}
})
console.log(a.latest);
那今天的介紹就到這裡
若有任何問題 或 內容有誤
都可以跟我說唷