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

I don't want to call the parent constructor. Can we do something about this?

I am trying to explore JS classes and I am getting error if I am not calling super().

ReferenceError: Must call super constructor in derived class before accessing ‘this’ or returning from derived constructor

My requirement is that I just want to call the constructor of the child class. Can I do that?

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 Employee {
  constructor() {
    console.log("I am an employee")
  }
}

class Learner extends Employee {
  constructor() {
    console.log("I am a learner")
  }
}

var learner = new Learner();

>Solution :

This is not possible and goes against OOP principles.

To access the same methods and properties in both Employee and Learner without invoking the other’s constructor, create a parent class named something like "Person" with separate constructors for Employee and Learner.

So, Employee extends Person and Learner extends Person. Then, place the shared methods and attributes inside Person.

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