js 属性getset

Posted 鹏飞万里

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 属性getset相关的知识,希望对你有一定的参考价值。

属性访问器有多种写法

一、像C#写实体类一样的写法


var attr={
        $x:10,//必须$开头
        get x() {
            return this.$x+1;
        },
        set x(val) {
            this.$x=val+2;
        }
    }
    console.log(attr.x); //11

    attr.x=21;

    console.log(attr.x);//24

二、setAttributegetAttribute


var shoop=document.getElementsById("psdf‘);
shoop.setAttribute("tittle","a lot of goods")

三、用Objct.defineProperty


var stu={
 _age=20;
editor=1
}
Object.defineProperty(stu,"age",{
    get:function(){
    return this._age;
    },
    set:function(newage){
        this._age=newage;
        this.editor++;
    }
})

stu.age=200;

以上是关于js 属性getset的主要内容,如果未能解决你的问题,请参考以下文章