Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent Javascript super constructor calling a method overridden by a derived class?

I’m new to JS and implementing a polymorphic class hierachy. It appears that within the super constructor (when called from a derived constructor), ‘this’ refers to the derived class, not the super class.

So, when the super constructor calls a method that the derived class has overridden, it calls the derived class version not the (original) super class version. This is not the behaviour I wanted, as it means the super constructor behaves differently for the same input parameters when it is called via the derived constructor.

A minimum working example is below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class A {
  constructor(x) {
    console.log("A constructor");
    this.x = x;
    this.foobar();
  }

  foobar() {
    console.log("A foobar");
  }
}

class B extends A {
  constructor(x, y) {
    console.log("B constructor");
    super(x);
    this.y = y;
  }

  foobar() {
    console.log("B foobar");
  }
}

let a = new A(123);
let b = new B(123, 456);

console.log output is:

A constructor

A foobar

B constructor

A constructor

B foobar   (I would have expected this to be 'A foobar')

Have I done something wrong, and if not is there a fairly straightforward way to ensure the original (super) method is always called by the super constructor?

Many thanks in advance for any advice.

PS: I have found similar question here:
How can I prevent calling a super function from the derived class function?

The answer given is to get the super constructor to check whether the instance is of the derived type and change behaviour accordingly. This seems cumbersome, but I could go with that if no-one can suggest a better solution.

>Solution :

To ensure the original method runs in the super constructor, call it directly using A.prototype.foobar.call(this). This avoids calling the overridden method in derived classes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading