Child.prototype = Parent.prototype vs Child.prototype = new Parent()

时间:2013-09-21 21:50:34

标签: javascript oop inheritance

在定义一些构造函数之后,例如Child,我见过以下两种形式:

Child.prototype = Parent.prototype;

Child.prototype = new Parent();

两者都正确吗?如果是这样,是否有理由偏爱另一个?

1 个答案:

答案 0 :(得分:6)

尽管@elclanrs的评论是正确的,而且现在您可能更喜欢Object.create,并选择在旧环境中对其进行填充,但对您的问题有一个明确的正确答案。

Child.prototype = new Parent();

远远优于

Child.prototype = Parent.prototype;

由于简单的原因,在后者中,您添加到子原型的任何属性也包含在父级中。什么时候

Dog.prototype = Animal.prototype;
dog.prototype.bark = function() {console.log("woof, woof");}
Cat.prototype = Animal.prototype;
var frisky = new Cat();
frisky.bark(); //=> woof, woof!

你有猫和狗住在一起......大规模的歇斯底里。

相关问题