JS之訪問器

來源:互聯網
上載者:User

標籤:

1.在對象中定義get,set訪問器屬性

<script>        var test = {            _name:"pmx",            _age:18,            _born:1990,            get name(){                return "name is "+this._name;               },            set name(value){                this._name = value;               },            get born(){                return this._born;            },            set born(value){                this._born = value;            },            get age(){                if(this._age > 100){                    return new Date().getFullYear() - this.born;                   }else{                    return this._age;                }               },            set age(value){                this._age = value;               }        }        console.log(test.age);        test.age = 2016;        console.log(test.age);</script>

 2.使用defineProperty給對象添加訪問器

<script>        var test = {            _name:"pmx",            _age:18,            _born:1990        }        Object.defineProperty(test,"name",{            get:function(){                return "name is "+this._name;            },            set:function(value){                this._name = value;            }        });        Object.defineProperties(test,{            age:{                get:function(){                    if(this._age > 100){                            return new Date().getFullYear() - this.born;                           }else{                        return this._age;                    }                       },                set:function(value){                    this._age = value;                   }            },            born:{                get:function(){                    return this._born;                },                set:function(value){                    this._born = value;                   }            }        });         console.log(test.age); //18         test.age = 2016;        console.log(test.age); //26</script>

3.在類中添加訪問器

<script>        function test(name,age){            this._name = name;            this._age = age;            Object.defineProperty(this,"name",{                get:function(){                    return "name is "+this._name;                   }            });        }        var tt = new test(‘pmx‘,26);        console.log(tt.name);</script>

 

JS之訪問器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.