爲了使畫面清晰:
在鏈中唯一
obj->"new B()"->"new A()" // where obj is the same as "new C()"
"new A()"
對象有財產constructor
。所有其他對象從原型鏈獲得constructor
屬性。
在代碼:
var A = function(){
}
A.prototype.name="A";
// A had not create "constructor" property for "new A()"
// so, looking at the prototype
// According to ECMAScript spec 13.2.10
// A.prototype.constructor == A
// thus
// "new A()".constructor == A
var B = function(){
}
B.prototype = new A();
B.prototype.name="B";
// B had not create "constructor" property for "new B()"
// looking at the prototype
// B.prototype is "new A()"
// as shown above
// "new A()".constructor == A
// thus
// B.prototype.constructor == A
// and at the end
// "new B()".constructor == A
var C = function(){
}
C.prototype = new B();
C.prototype.name="C";
// C had not create "constructor" property for "new C()"/"obj"
// looking at the prototype
// C.prototype is "new B()"
// looking up to "new B()".prototype
// "new B()".prototype is "new A()" as shown above
// "new A()".constructor == A
// and finally
// C.prototype.constructor == A
obj = new C();
print(obj.name);
print(obj.constructor.prototype.name);
print(obj.constructor == A);
因此,作爲寫mellamokb我們應該覆蓋(如果更精確的創建,)constructor
財產。
構造函數屬性在原型對象中定義,並且在爲其分配時指定其所有成員。任何你想擁有不同值的成員都必須被定義,否則你將繼承構造函數,toString,valueOF,以及原型所包含的其他東西。 – kennebec 2011-05-13 16:07:09
謝謝,我意識到這已經 – nahab 2011-05-13 16:20:08