码迷,mamicode.com
首页 > Web开发 > 详细

JS之访问器

时间:2016-09-13 13:09:59      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

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之访问器

标签:

原文地址:http://www.cnblogs.com/bibiafa/p/5867791.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!