在js中,任何一個對象都有一個prototype屬性,在js中記作:_proto_。學習
好比,咱們建立一個對象:prototype
<!-- lang: js --> var foo = { x:1, y:2 }
雖然看起來咱們只爲foo對象建立了兩個屬性,實際上,它還有一個屬性_proto_,如圖: code
即便咱們不定義_proto_,在js中也會預留一個屬性。對象
若是咱們定義一個空對象,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中沒有,它便會順着原型鏈向上查找。ip
此時,咱們給obj定義z值:原型鏈
<!--lang:js--> obj.z =10; //運行結果 obj;//返回foo {x: 1, y: 2, z: 10}
接着,刪除z屬性:get
<!--lang:js--> delete obj.z //運行結果 obj;//結果是:foo {x: 1, y: 2, z: 3}
可見,咱們的刪除操做也只是obj上的,並不會對其原型產生影響。原型
屬性定義:調用Object.defineProperty(object, propertyname, descriptor),三個項都是必須的。it
<!-- lang: js --> Object.defineProperty(obj,'title',{ value:'helloworld', });
其中,defineProperty()中的descriptor有四個屬性,分別爲:
此外,咱們還能夠查看屬性,經過: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'} }}
若是咱們已經定義了這些屬性,那麼如何修改呢,其實也很簡單,只要再次定義一下就能夠了。
先記錄這些,繼續學習,繼續補充筆記。