What is the correct prototype affectation in javascript inheritance?

前端 未结 2 1622
轮回少年
轮回少年 2020-12-18 06:14

I read several articles on js inheritance already (this one, this one, this one, etc.)

In this article from Mozilla, \"classic\" inheritance is shown as this : (I un

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 07:17

    What is the correct way to do classical inheritance in JavaScript

    In this answer i explained the difference between 1 and 2 showing why 2 is the best way to emulate classical inheritance in JavaScript.

    In short, in solution 1 children inherit from an instance of the parent. In solution 2 the class of the children (Derived.prototype) inherits from the class of the parent(Base.prototype). This imposes severe limitations on the parent, because it must be called with 0 arguments.

    The 3rd solution is even worse because the prototypes of the Derived and the Base class are the same object, so no method overriding can take place. Even worse, a method defined in Derived.prototype will be available for all Base instances and if a method with the same name had been declared on Base.prototype, it would simply be replaced.

    Conclusion: 2 is the true way to do classical inheritance in JavaScript.

    Is setting the constructor property needed

    Setting the constructor property on the prototype makes it accessible to all instances. That is simply for convenience, the inheriting part works without it.

提交回复
热议问题