为了转生而点技能-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运算完毕的值
https://ithelp.ithome.com.tw/upload/images/20211213/20143762wJh0jKqq3O.jpghttps://ithelp.ithome.com.tw/upload/images/20211213/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属性颜色不同
https://ithelp.ithome.com.tw/upload/images/20211213/20143762kYuaEczPY0.jpg
console.log(Object.getOwnPropertyDescriptor(wallet, 'save'));检查该属性的特徵。

https://ithelp.ithome.com.tw/upload/images/20211213/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

https://ithelp.ithome.com.tw/upload/images/20211213/20143762oZbzEK9Ap3.jpg




<<:  Snowflake SnowPro-Core Dumps - The Best Option To Pass Exam

>>:  Between Two Sets

[DAY 30] 复刻 Rails - View 威力加强版 - 2

终於到最後一天了,那就不罗嗦直接进入正题吧! 关於 rendering.rb 之前我们的做法是把 r...

Day 04: 进入主题前的补充:SOLID

为什麽要补充? 当决定铁人赛的题目是 Design Patterns 时,除了先 Google 看看...

[13] 制作离开功能

先制作离开应用程序的功能 在流程控制 class 的 mainMenu 追加个判断 然後加个离开程序...

Day 15 : 特徵工程 tf.Tramsform 介绍

特徵工程是机械学习相当重要的一环,有处理数据以及实行 ML/DL 任务经验者对特徵工程一定不陌生,...

Day 7. Hashicorp Nomad: Inspect a job

Hashicorp Nomad: Inspect a job 当一套工具有一个好的Web UI可以使...