Setter:存值。
**方法一:**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
Getter:取值。
**方法一:**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