Why is new Parent() often used to initialize proto

2019-05-21 01:27发布

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条回答
混吃等死
2楼-- · 2019-05-21 01:55

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.

查看更多
登录 后发表回答