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);
Run Code Online (Sandbox Code Playgroud)
此代码提供下一个输出:
C
A
true
Run Code Online (Sandbox Code Playgroud)
为什么这里的obj.constructor是A而不是C?
曾经出现在此代码示例,您必须手动重置.constructor使用继承时,或你的构造被覆盖,当你调用属性new A()或new B():
B.prototype = new A();
B.prototype.constructor = B; // need this line to fix constructor with inheritance
Run Code Online (Sandbox Code Playgroud)
这是一个工作样本:http://jsfiddle.net/93Msp/.
希望这可以帮助!