The JavaScript super keyword

By

Learn what the super keyword does in JavaScript classes, how it calls the parent class constructor when you extend a class, and where you can use it.

~~~

When we work with classes in JavaScript, it’s common to use the super keyword. It does two jobs: super() calls the constructor of the parent class, and super.method() calls a method defined on the parent class.

Let’s see both, starting from the beginning.

Suppose you have a class Car:

class Car {

}

and in this class we have a constructor() method:

class Car {
  constructor() {
    console.log('This is a car')
  }
}

The constructor method is special because it is executed when the class is instantiated:

const myCar = new Car() //'This is a car'

You can have a Tesla class that extends the Car class:

class Tesla extends Car {

}

The Tesla class inherited all the methods and properties of Car, including the constructor method.

We can create an instance of the Tesla class, creating a new myCar object:

const myCar = new Tesla()

And the original constructor in Car is still executed, because Tesla does not have one of its own.

You must call super() in a child constructor

Now watch what happens when we define our own constructor in Tesla, without calling super():

class Tesla extends Car {
  constructor() {
    console.log('This is a Tesla')
  }
}

const myCar = new Tesla()

This throws:

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

The rule: when a class extends another and defines its own constructor, that constructor must call super() before it finishes, and before it touches this. The parent has to build the object first.

Here is the working version:

class Tesla extends Car {
  constructor() {
    super()
    console.log('This is a Tesla')
  }
}

Calling

const myCar = new Tesla()

will now execute 2 console logs. First the one defined in the Car class constructor, the second the one defined in the Tesla class constructor:

'This is a car'
'This is a Tesla'

Passing parameters to the parent

If the parent constructor accepts parameters, super() is how you pass them up:

class Car {
  constructor(brand) {
    this.brand = brand
  }
}

class Tesla extends Car {
  constructor() {
    super('Tesla')
  }
}

const myCar = new Tesla()
myCar.brand //'Tesla'

Calling parent methods

Note that super() as a call only works inside the constructor. In regular methods you use super.method() instead, to run the parent’s version of a method you’re overriding:

class Car {
  describe() {
    return 'A car'
  }
}

class Tesla extends Car {
  describe() {
    return super.describe() + ', electric'
  }
}

new Tesla().describe() //'A car, electric'

This way you extend the parent’s behavior instead of replacing it entirely.

~~~

Related posts about js: