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

二、setAttribute\getAttribute


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)

屬性標簽關系圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM