obj.constructor返回最顶层的构造函数而不是直接的父构造函数

时间:2013-12-01 16:41:47

标签: javascript prototypal-inheritance

在玩javascript继承时遇到了这个小混乱。

 function A() {}

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

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

 var x = new C();
 x.construction // -> returns A in chrome console.

我期待x.constructor为C(甚至可能是B),但不是一直到A(为什么甚至停在A而不是显示对象)

1 个答案:

答案 0 :(得分:0)

完全替换prototype对象后,原始constructor引用将与原始prototype对象一起删除,而是继承自new A()等。

function B() {}

console.log(B.prototype.constructor === B); // true

B.prototype = new A();

console.log(B.prototype.constructor === B); // false
console.log(B.prototype.constructor === A); // true

因此,您必须在设置constructor之后重置prototype

function A() {}

function B() {}
B.prototype = new A();
B.prototype.constructor = B;

function C() {}
C.prototype = new B();
C.prototype.constructor = C;