JavaScript中的屬性操作

來源:互聯網
上載者:User

標籤:

JavaScript中的屬性操作 一、 原型鏈

在js中,任何一個對象都有一個prototype屬性,在js中記做:_proto_。

比如,我們建立一個對象:

<!-- lang: js -->var foo = {    x:1,    y:2}

雖然看起來我們只為foo對象建立了兩個屬性,實際上,它還有一個屬性_proto_,

即使我們不定義_proto_,在js中也會預留一個屬性。

如果我們定義一個Null 物件,foo

<!-- lang: js -->foo = function(){}foo.prototype.z = 3;var obj = new foo();obj.x = 1;obj.y =2;//運行結果obj //結果是:foo {x: 1, y: 2, z: 3}

很顯然。我們並沒有給obj定義z值,但是卻返回了z值,從這可以看出,obj中沒有,它便會順著原型鏈向上尋找。

此時,我們給obj定義z值:

<!--lang:js-->obj.z =10;//運行結果obj;//返回foo {x: 1, y: 2, z: 10}

接著,刪除z屬性:

<!--lang:js-->delete obj.z//運行結果obj;//結果是:foo {x: 1, y: 2, z: 3}

可見,我們的刪除操作也只是obj上的,並不會對其原型產生影響。

二、屬性操作

屬性定義:調用Object.defineProperty(object, propertyname, descriptor),三個項都是必須的。

<!-- lang: js -->Object.defineProperty(obj,‘title‘,{    value:‘helloworld‘,});

其中,defineProperty()中的descriptor有四個屬性,分別為:

  • value //值
  • enumerable //是否允許for-in進行遍曆,預設為true
  • configurable //是否允許使用delete進行操作並重新定義,預設為true
  • writable //是否允許修改,more為true

此外,我們還可以查看屬性,通過:Object.getOwnPropertyDescriptor(object, propertyname),兩個項都是必須。如:

<!--lang:js-->var foo = {    title:‘hello‘};console.log(Obejct.getOwnPropertyDescriptor(obj,‘title‘));//運行結果是//Object {value: "hello", writable: true, enumerable: true, configurable: true}

其次,我們也可以通過for-in來遍曆輸出每項屬性。

<!--lang:js-->var des = Object.getOwnPropertyDescriptor(obj,‘title‘);for(var key in des){    console.log(key+‘:‘+des[key]);}//運行結果//value:hello//writable:true//enumerable:true//configurable:true

補充一點剛才定義屬性用的是Object.defineProperty(),如果我們想一次性定義多個屬性,只要修改一點就可以:

<!--lang:js-->Object.defineProperties{person,{    name:{value:‘Gavin‘,writable:false,enumerable:false},    salaty:{value:5000,writable:true,enumerable:false},    sex:{value:‘man‘}}}

如果我們已經定義了這些屬性,那麼如何修改呢,其實也很簡單,只要再次定義一下就可以了。

先記錄這些,繼續學習,繼續補充筆記。

JavaScript中的屬性操作

聯繫我們

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