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

那今天的介绍就到这里
若有任何问题 或 内容有误
都可以跟我说唷/images/emoticon/emoticon41.gif


<<:  前端工程学习日记第14天

>>:  [Report] 怎麽让筛选条件可以复选

Day 9 运算宝石:EC2 重点架构

今天我们要来介绍 EC2 的基本架构,那我们开始吧! EC2 Instance由许多重要元件组成,...

Day 13:来把静态档案加入 Angular CLI 建立的专案吧!

把静态档案加到 Angular 专案中 前一篇,我们已经学会用 Angular CLI 建立元件及范...

Day 20:全域、路由、元件内-Navigation Guards

之前有预告过,发送 API 的时机点需视不同情境及 UX 体验规划而定,因此除了选择在元件内的生命周...

卡夫卡的藏书阁【Book22】- Kafka - KafkaJS 消费者 4

“Love is, that you are the knife which I plunge i...

Day28-台湾菜鸟工程师除错之卷三

由於没有发布紧急事态宣言 但是为了救旅游业却推出了旅游补助方案(goto キャンペーン) 当时候的...