2010-10-10 94 views
4

我觉得这段代码的行为令人费解,为什么child的构造函数不是Child?有人可以向我解释这个吗?javascript对象模型:奇怪的构造函数属性

function Parent() { 
    this.prop1 = "value1"; 
    this.prop2 = "value2"; 
} 

function Child() { 
    this.prop1 = "value1b"; 
    this.prop3 = "value3"; 
} 
Child.prototype = new Parent(); 

var child = new Child(); 

// this is expected 
console.log(child instanceof Child); //true 
console.log(child instanceof Parent); //true 

// what?? 
console.log(child.constructor == Child); //false 
console.log(child.constructor == Parent); //true 
+0

这个问题似乎是[this one]的一个副本(http://stackoverflow.com/questions/2479349/constructors-and-inheritance-in-js) - 但我觉得这个问题的答案更有用。 + 1s全部:) – 2010-10-29 02:22:04

回答

5

由于尖指出,in his answer

的“构造”特性是 引用创建 对象的原型,而不是对象本身 功能。

通常的方式来处理,这是分配给prototype

function Parent() { 
    this.prop1 = "value1"; 
    this.prop2 = "value2"; 
} 

function Child() { 
    this.prop1 = "value1b"; 
    this.prop3 = "value3"; 
} 
Child.prototype = new Parent(); 

// set the constructor to point to Child function 
Child.prototype.constructor = Child; 

var child = new Child(); 

// this is expected 
console.log(child instanceof Child); //true 
console.log(child instanceof Parent); //true 

// corrected 
console.log(child.constructor == Child); // now true 
console.log(child.constructor == Parent); // now false 

console.log(Child.prototype.constructor); // Child 
console.log(Parent.prototype.constructor); // Parent 

我不能建议后,以增加对象的原型constructor财产斯托扬斯特凡的Object Oriented JavaScript足够覆盖原型和继承的一些细节(如果可以的话,获得第二版,因为它解决了第一版的一些批评)。

+0

谢谢你的提示,也许我会订购它,虽然第二版似乎还没有准备好。 – einarmagnus 2010-10-10 22:41:05

+1

这个解决方案意味着如果我要创建一个Child的兄弟,即另一个'函数Sibling(){}; Sibling.prototype =/*表达式* /; var sibling = new Sibling()',那么'expression'必须是'new Parent()',而不是与Child相同的父对象,即'Child.prototype!= Sibling.prototype'。这是通常的做法吗?我喜欢原型继承的哲学,但这似乎是一个非常复杂的做法。 – einarmagnus 2010-10-10 22:52:16

+0

是的,您无法将'Parent'的同一个实例分配给'Child'和'Sibling'的'prototype',因为对Child或Sibling的'prototype'所做的任何更改都会影响另一个。例如,设置其中一个的'constructor'将会改变它们。 – 2010-10-29 19:56:09

4

的“构造”特性是创建对象的原型,而不是对象本身的函数的引用。

+0

在这种情况下,它来自'Parent'构造函数返回的对象并分配给'Child.prototype' – 2010-10-10 19:26:36

+0

正确的。我一直在努力寻找一个几个月前我读过的网站/博客,它有一个很好的解释(有很好的图表),如果我这样做,我会链接它。 – Pointy 2010-10-10 19:29:25

+0

不,对象本身是“孩子”,但它是由“孩子”构建的(注意大写字母)。这似乎是JS的一个(另外的)设计缺陷,它将指向对象的原型的构造函数而不是对象的构造函数。 – einarmagnus 2010-10-10 20:47:06