【发布时间】:2019-01-24 13:29:43
【问题描述】:
我想使用 super 的构造函数将子类实例传递给超类,但是我得到了这个错误
super(this);
在超类构造函数调用之前不允许这样做
为什么我收到了这个错误,还有如何我可以解决这个问题
class Parent
{
constructor(child)
{
this.child = child;
}
//...somewhere in code
//child.doSomething();
}
class Child extends Parent
{
constructor()
{
super(this); // <==== the error here
}
doSomething = () =>
{
//...
}
}
【问题讨论】:
-
这不是您在 JavaScript(或一般情况下)中实现继承的方式;这更像是作曲。在继承方面,如果
doSomething仅存在于Child,则不应从Parent调用它(因为并非所有子类都必须拥有它)。在组合方面,Child不需要extend Parent,也不应该负责将自身传递给构造函数。 -
设置
this.child = this没有意义。你的目标是什么?您可以拨打this.doSomething() -
或者你想要
class Child { constructor() { this.parent = new Parent(this); } … },而不是extends Parent? -
@Ali 您可能想发布一个新问题,在其中发布带有实际问题的实际代码。是的,当您在同一个子实例上调用它们时,
this.child在父和子方法/构造函数中是相同的。您是否来自不同的语言,需要通过“继承”属性的类来区分属性?
标签: javascript ecmascript-6 es6-class