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;

属性标签

  1. configurable //是否可以修改属性标签或delete
  2. writable //是否可写
  3. enumerable //是否可枚举(遍历for的时候必须是可枚举的或object.keys(objs))
  4. get/set 访问器,上面写过了(getset访问器=>看三object.defineProperty)

属性标签关系图

原文地址:https://www.cnblogs.com/wangSOA/p/9744202.html