原型继承。 obj-> C-> B-> A,但是obj.constructor是A.为什么?

时间:2011-05-13 14:52:11

标签: javascript

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);

此代码提供下一个输出:

C
A
true

为什么这里的obj.constructor是A而不是C?

3 个答案:

答案 0 :(得分:7)

this code sample所示,您必须在使用继承时手动重置.constructor属性,或在调用new A()new B()时覆盖您的构造函数:< / p>

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

以下是一份工作样本:http://jsfiddle.net/93Msp/

希望这有帮助!

答案 1 :(得分: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属性。

答案 2 :(得分:0)

我认为这篇文章解释了原型继承中构造函数的一个很好的协议

http://phrogz.net/js/classes/OOPinJS2.html