问题
I want to pass child class instance to super class using super's constructor but I'm get this error
super(this);
this is not allowed before superclass constructor invocation
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 = () =>
{
//...
}
}
回答1:
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.
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.
回答2:
In the child's constructor method, the parent's constructor must be called before accessing this
. The superclass' constructor will have access to this
anyway, since you are constructing an instance of the superclass - though it will not have access to any other initialization that your child constructor may yet do.
来源:https://stackoverflow.com/questions/51896505/this-is-not-allowed-before-superclass-constructor-invocation