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?
解决方法
如
this code sample所示,在使用继承时必须手动重置.constructor属性,或者在调用new A()或new B()时重写构造函数:
B.prototype = new A(); B.prototype.constructor = B; // need this line to fix constructor with inheritance
这是一个工作样本:http://jsfiddle.net/93Msp/.
希望这可以帮助!