Call parent function which is being overridden by child during constructor chain in JavaScript(ES6) [duplicate]

You seem to be operating under a misconception that there are two objects A and B when you are in the constructor of the derived class B. This is not the case at all. There is one and only one object. Both A and B contribute properties and methods to that one object. The value of this will be the same in the constructor for B as it is in the constructor for A during the creation of an object of class B.

The ES6 class syntax is just sugar over the ES5 method of using prototypes for object types and, in fact, the prototype is still used under the covers. As such, when you define a method foo in a derived class like you do in class B, it is still assigning to the prototype and that assignment overrides any method of the same name that might already exist on the prototype that came from the parent definition. This is why refers to the class B version of foo. If you want to reach the class A version of foo, then you will have manually specify that using super as you appear to already know.

As for your specific questions:

It seems that this still points to child B while constructing in
parent A. That’s why I can’t reach parent A’s foo.

child B and parent A are not separate objects. There is one object that both parent A and child B reference. parent A and child B methods or constructors will see the exact same value of this.

How do I make this to call parent version function which is being
overridden by child during constructor chain?

You use super to reference parent methods directly as you appear to already know.

Or is there any better solution when it comes to scenario like this?

super is the solution.

FYI, this is a pretty good discussion on ES6 classes including how super works: Classes in ECMAScript 6 (final semantics). Section 4.4 seems particularly relevant to your question/understanding.

Leave a Comment