skip to Main Content

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?

class Employee {
  constructor() {
    console.log("I am an employee")
  }
}

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

var learner = new Learner();

2

Answers


  1. 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.

    Login or Signup to reply.
  2. As you create a Learner instance, you create an Employee instance. It is expected that the constructor is run when you create a class instance.

    If you have scenarios where you don’t want to run the code in that constructor, then apparently that code is not really code that is essential for the construction of the object and should be moved elsewhere.

    For instance, like this:

    class Employee {
        outputName() {
            console.log("I am an employee")
        }
    }
    
    class Learner extends Employee {
        outputName() {
            console.log("I am a learner")
        }
    }
    
    var learner = new Learner();
    learner.outputName();

    Or, make the Employee constructor more generic so it does what you need for any subclassed instance as well. For instance,

    function addArticle(subject) {
        return ("aeiouAEIOU".includes(subject[0]) ? "an " : "a ") + subject;
    }
    
    class Employee {
        constructor() {
            const className = addArticle(this.constructor.name);
            console.log("I am " + className);
        }
    }
    
    class Learner extends Employee {
    }
    
    var learner = new Learner();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search