js程式設計03——物件導向

來源:互聯網
上載者:User

標籤:

ECMAScript中有2中屬性:資料屬性、訪問器屬性。

資料屬性是為了指定某對象的指定key上的一些行為,比如value是否可刪除、修改、key可迴圈遍曆等特點。而訪問器屬性不包含資料值,包含一堆get、set方法(非必須),讀取存取對象屬性時,採用getter、setter分別實現。

資料屬性包括:

  • Configurable:表示能否通過delete刪除該屬性,或者修改重新定義屬性,預設false
  • Enumerable:表示for-in迴圈返回屬性,預設false
  • Writable:表示能否修改屬性值,預設false
  • Value:包含這個資料的值

一旦把屬性定義為不可配置的,就不能再把它變回可配置了:

var person = {};Object.defineProperty(person,"name",{  configurable:false,  value:"admin"});//直接報錯:TypeError: Cannot redefine property: nameObject.defineProperty(person,"name",{  configurable:true,  value:"test"})

因為這裡的"name"屬性已經定義為configurable:false,即不可重新修改屬性,所以再次修改會報錯。

var person = {  name:"我是沒修改前的值",  _age:22};Object.defineProperty(person,"age",{  get:function(){    return this._age;  },  set:function(newValue){    if(newValue > this.age){      this._age = newValue;      this.name += " 哈哈,我是修改後的name值";    }  }});person.age = 22;console.log(person);person.age = 23;console.log(person);

執行結果:

注意:這裡的屬性底線是一種記號,表示只能通過對象方法訪問的屬性,這樣一來,對該屬性的讀取會使用get、set來實現,如果只指定get表示不能寫入,只指定set表示不能讀取。

那麼,如何一次性聲明定義多個屬性呢,如下:

var person = {};Objetc.defineProperties(person,{  _name:{    value:"chaozhou"  },  age:{    value:23,    set:function(newValue){      this.age = newValue;    },    get:function(){      return this.age;    }  },  sex:{    value:"男"  }});

 

js程式設計03——物件導向

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.