【问题标题】:Child.prototype = Parent.prototype vs Child.prototype = new Parent()Child.prototype = Parent.prototype vs Child.prototype = new Parent()
【发布时间】:2013-09-21 21:50:34
【问题描述】:

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

Child.prototype = Parent.prototype;

Child.prototype = new Parent();

都正确吗?如果是这样,是否有理由更喜欢其中一个?

【问题讨论】:

  • 当今首选方式:Child.prototype = Object.create(Parent.prototype)
  • 在第一个版本中,两个构造函数共享同一个原型。这意味着 Child 不能有自己的原型方法。如果您使用相同的方法创建 GrandChild 原型,它实际上会继承自 Parent。
  • 结合elclanrs所说的,你有时也会在Child的开头看到Parent.call(this);

标签: javascript oop inheritance


【解决方案1】:

尽管@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!

你有猫和狗住在一起......集体歇斯底里。

【讨论】:

    猜你喜欢
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多