iT邦幫忙

0

為了轉生而點技能-JavaScript,day20(簡易Setter、Getter設定

  • 分享至 

  • xImage
  •  

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




圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言