Search code examples
javascriptinheritancesubclasssuperclass

Why does using super(qualifications) in a subclass throw a ReferenceError when it was defined in the superclass?


class SchoolEmployee {
  constructor(name, qualifications) {
    this._name = name;
    this._qualifications = qualifications;
    this._holidaysLeft = 21;
  }

  get name() {
    return this._name;
  }

  get qualifications() {
    return this._qualifications;
  }

  get holidaysLeft() {
    return this._holidaysLeft;
  }

  takeHolidays(days) {
    this._holidaysLeft -= days;
  }
}

class Teacher extends SchoolEmployee {
  constructor(name, qualifications, subject) {
    super(name);
    super(qualifications); //THIS IS THE ERROR
    this._subject = subject;
  }

  get name() {
    return this._name;
  }

  get qualifications() {
    return this._qualifications;
  }

  get subject() {
    return this._subject;
  }
}

let John = new Teacher('John', ['Maths', 'Physics'], 'Maths');

SchoolEmployee is the super class where I have defined what 'qualifications' is. From my knowledge, writing super(qualifications) calls the constructor of the super class where it was previously defined. Currently I am learning Javascript and i don't understand what went wrong. Can anybody help me?


Solution

  • As you can look up on mdn super() calls the constructor of the parent class and you are calling it twice. What you probably want is

    class Teacher extends SchoolEmployee {
        constructor(name, qualifications, subject) {
            super(name, qualifications);
            this._subject = subject;
        }
    }