Why is new Parent() often used to initialize prototypes of children instead of Object.create(Parent.prototype)?

早过忘川 提交于 2019-12-22 12:13:30

问题


In the middle of Mozilla documentation page it switches (without clear enough explanation) examples from

WorkerBee.prototype = Object.create(Employee.prototype);

to

WorkerBee.prototype = new Employee;

Second form new Employee will initialize prototype of WorkBee with properties that are supposed to exist only in instances of WorkBee.

Why is second form being used in so many examples of JavaScript inheritance ? Isn't it undesired to give different status to inherited properties vs own properties ?

Status of Employee property name inside WorkBee is different than property projects because name is defined in WorkBee.prototype.name, while projects is defined on WorkBee instance.

In general, why would anyone ever want to use constructor of non-abstract class X to initialize prototype of derived class Y in JavaScript ?

In my opinion, both constructors should only be used to initialize instances of X and Y and if Y is derived from X then constructor X should initialize instances of Y, not prototype of Y. But if X is abstract, which means we don't expect to have instances of X, only then we can potentially use X constructor as a place to put initialization of prototypes of derived classes.


回答1:


Why is second form being used in so many examples of JavaScript inheritance?

Because we didn't get rid of it, and it keeps spreading. See also here for some history.

Isn't it undesired to give different status to inherited properties vs own properties?

Yes, absolutely.



来源:https://stackoverflow.com/questions/39911926/why-is-new-parent-often-used-to-initialize-prototypes-of-children-instead-of-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!