gpt4 book ai didi

javascript - ES6 - 构造函数中需要 Super

转载 作者:行者123 更新时间:2023-11-28 15:09:35 24 4
gpt4 key购买 nike

class Overflow {}
class Stack extends Overflow {
constructor() {
super();
}
}

let stack = new Stack();

https://plnkr.co/edit/JqRfuDAav9opvapwCGpT?p=preview

如果我使用constructor(),我必须调用super()总是

为什么构造函数中没有调用super() auto?

编辑:super()在这里调用基本构造函数AND设置原型(prototype)吗?看来是错误的。编辑:为什么需要 super() ?即使我无意调用基本构造函数。

最佳答案

Why isn't super() auto called in constructor?

因此您可以决定在构造函数中的何处调用它。这是完全有效的,例如:

constructor(foo) {
let bar;
if (foo) {
bar = /*...*/;
} else {
bar = /*...*/;
}
super(bar);
}

...假设在调用 super 之前没有任何代码使用 this(或 super.xyz)。

是的,可以这样定义语言:如果您在构造函数中根本没有对 super 进行任何调用,它会自动添加一开始就为您提供(a'la Java),但他们只是决定不这样做。

Is super() here calling the base constructor AND setting the prototype? Seems wrong.

不,它正在调用基本构造函数。原型(prototype)是在调用构造函数之前设置的。它就像这个旧的 ES5 代码一样:

function Derived() {
Base.call(this);
}

...在:

function Base() {
}

function Derived() {
Base.call(this);
}
Derived.prototype = Object.create(Base.prototype);
Derived.prototype.constructor = Derived;

Why is super() required? Even when I've no intention of calling the base constructor.

如果您无意调用基构造函数,那么您的子类不是子类,也不应该扩展基构造函数。在严格类型语言中,您可能会将基类(或基类的子集)设置为接口(interface),并让您的类实现该接口(interface)而不是子类化。在 JavaScript 中,不需要,只需让它像你想要的鸭子一样嘎嘎叫即可。如果 instanceof 关系很重要,请创建一个新的基类,该基类的作用类似于接口(interface),但在任何地方都不执行任何操作,并让旧基类和您的类直接将其子类化。

关于javascript - ES6 - 构造函数中需要 Super,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37144920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com