为什么新的Parent()经常用于初始化子项的原型而不是Object.create(Parent.prototype)? [英] Why is new Parent() often used to initialize prototypes of children instead of Object.create(Parent.prototype)?

查看:138
本文介绍了为什么新的Parent()经常用于初始化子项的原型而不是Object.create(Parent.prototype)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mozilla文档页面的中间

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

WorkerBee.prototype = new Employee;

第二种形式新员工将初始化原型具有应该仅存在于WorkBee实例中的属性的WorkBee。

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

为什么在如此多的JavaScript继承示例中使用了第二种形式?
是不是不希望为继承的属性和自己的属性赋予不同的状态?

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 ?

WorkBee中Employee属性名称的状态与属性项目不同,因为name在WorkBee.prototype.name中定义,而project在WorkBee实例上定义。

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.

一般来说,为什么有人会想要使用非抽象类X的构造函数来初始化JavaScript中派生类Y的原型?

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

在我看来,两个构造函数只应用于初始化X和Y的实例,如果Y是从X派生的,那么构造函数X应该初始化Y的实例,而不是Y的原型。
但是如果X是抽象的,这意味着我们不希望有X的实例,只有这样我们才可能使用X构造函数作为放置派生类原型初始化的地方。

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.

推荐答案


为什么在如此多的JavaScript继承示例中使用第二种形式?

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

因为我们没有摆脱它,它保持了sprea丁。有关历史信息,另请参见此处

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?

是的,绝对。

这篇关于为什么新的Parent()经常用于初始化子项的原型而不是Object.create(Parent.prototype)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆