问题描述
我想使用super的构造函数将子类实例传递给超类,但出现此错误
I want to pass child class instance to super class using super's constructor but I'm get this error
super(this);
为什么,我也收到此错误,还如何我可以解决此问题
Why i'm getting this error , also how could I resolve this issue
class Parent
{
constructor(child)
{
this.child = child;
}
//...somewhere in code
//child.doSomething();
}
class Child extends Parent
{
constructor()
{
super(this); // <==== the error here
}
doSomething = () =>
{
//...
}
}
推荐答案
无需将 this
传递给 super()
,因为 this
在超类构造函数中,将是对同一对象的引用.回想一下,您的类层次结构将合作对单个新对象执行初始化.
There's no need to pass this
to super()
because this
inside the superclass constructor will be a reference to the same object. Recall that your class hierarchy will cooperate to perform initialization on a single new object.
对 super()
的调用必须先于对 this
的任何引用,包括在 super()
参数列表中.为什么?因为为了模仿其他OO语言的行为,必须是这样的情况,即类层次结构中最顶层的初始化程序首先要使用新对象.父(或高级")初始化器应能够假定该级别的原型方法具有基类期望的语义,因为它不知道"子类对其原型进行了哪些操作等.可以修改新对象并覆盖基类原型方法(或类似形式的其他方法),这会造成混乱.
Calls to super()
must come before any reference to this
, including in the super()
argument list. Why? Because in order to mimic behavior of other OO languages, it must be the case that the top-most initializer in the class hierarchy gets its hands on the new object first. The parent (or "senior") initializer should be able to assume that prototype methods at that level have the semantics the base class expects, since it doesn't "know" what subclasses might have done with their prototypes etc. If a subclass initializer could modify the new object and override a base class prototype method (or something else of that flavor), it'd be chaos.
这篇关于在超类构造函数调用之前,这是不允许的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!