2011-05-13 29 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财产。

相关问题