为了转生而点技能-JavaScript,day20(简易Setter、Getter设定

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运算完毕的值
http://img2.58codes.com/2024/20143762wJh0jKqq3O.jpghttp://img2.58codes.com/2024/201437625TCX58nors.jpg

方法二:

        var wallet = {            total: 100,        };        Object.defineProperty(wallet, 'save', {            get: function () {                return this.total / 2            },        });        console.log(wallet);     //50

Object.defineProperty建立Getter,在chrome浏览器会出现save属性的颜色跟total属性颜色不同
http://img2.58codes.com/2024/20143762kYuaEczPY0.jpg
console.log(Object.getOwnPropertyDescriptor(wallet, 'save'));检查该属性的特徵。

http://img2.58codes.com/2024/201437620wieWtKwpz.jpg

修改后,

        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

http://img2.58codes.com/2024/20143762oZbzEK9Ap3.jpg




关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章