JS Getter 与 Setter DAY71

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);

那今天的介绍就到这里
若有任何问题 或 内容有误
都可以跟我说唷http://img2.58codes.com/2024/emoticon41.gif


关于作者: 网站小编

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

热门文章