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);
那今天的介绍就到这里
若有任何问题 或 内容有误
都可以跟我说唷