2011-05-13 53 views
7
var print = function(text){ 
    document.write(text); 
    document.write("</br>"); 
} 

var A = function(){ 
} 
A.prototype.name="A"; 

var B = function(){ 
} 
B.prototype = new A(); 
B.prototype.name="B"; 

var C = function(){ 
} 
C.prototype = new B(); 
C.prototype.name="C"; 

obj = new C(); 
print(obj.name); 
print(obj.constructor.prototype.name); 
print(obj.constructor == A); 

該代碼給出了一個輸出:原型繼承。 obj-> C-> B-> A,但obj.constructor是A.爲什麼?

C 
A 
true 

爲什麼obj.constructor這裏是A和不是C?

+0

構造函數屬性在原型對象中定義,並且在爲其分配時指定其所有成員。任何你想擁有不同值的成員都必須被定義,否則你將繼承構造函數,toString,valueOF,以及原型所包含的其他東西。 – kennebec 2011-05-13 16:07:09

+0

謝謝,我意識到這已經 – nahab 2011-05-13 16:20:08

回答

7

this code sample看到的,你必須使用繼承時,或你的構造被覆蓋,當你調用new A()new B()手動重置.constructor屬性:

B.prototype = new A(); 
B.prototype.constructor = B; // need this line to fix constructor with inheritance 

這裏是工作示例:http://jsfiddle.net/93Msp/

希望這會有所幫助!

+0

有趣的 - 任何想法,爲什麼這是可取的行爲? – 2011-05-13 15:05:16

+1

鑑於JavaScript中的面向對象是一大難題,這樣的事情是可以預料的。 – mellamokb 2011-05-13 15:05:54

+0

是的。這有助於) – nahab 2011-05-13 15:15:17

4

爲了使畫面清晰:

在鏈中唯一

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財產。

相關問題