js中構造函數與原型(圖解)

本文爲閱讀博文http://clarkdo.github.io/javascript/2014/08/21/17/後總結而得

①:

f1._proto_==Foo.prototype//true

②:

function Foo() { } ; 
var f1 = new Foo();

Foo.prototype.x = "hello";
f1.x   //=> hello
Foo.x //=> undefined


注:所有對象會自動讀取原型鏈的屬性, 就像那些屬性是對象自身定義的.若對象中定義了與原型鏈中重複的屬性,則原型鏈上的屬性會隱藏。

舉個栗子:

function foo() { } 
f1 = new foo();
f2 = new foo();
foo.prototype.x = "hello";

f1.x  => "hello"
f2.x  => "hello";

f1.x = "goodbye";   //setting f1.x hides foo.prototype.x

f1.x  => "goodbye"  //hides "hello" for f1 only
f2.x  => "hello"
  
delete f1.x
f1.x  => "hello";   //foo.prototype.x is visible again to f1.




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章