JavaScript super keyword

When we use classes in JavaScript, we usually usesuperKey words.

In this article, I want to clarify its role.

Suppose you have a classCar:

class Car {

}

In this lesson, we have aconstructor()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 oneTeslaExpandedCarclass:

class Tesla extends Car {

}

ThisTeslaClass inheritedCar, Includingconstructormethod.

We can create an instanceTeslaClass, create a newmyCarpurpose:

const myCar = new Tesla()

And the original constructorCarStill executed becauseTeslaThere is no one of its own.

We can coverconstructor()Method inTeslaclass:

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

with

const myCar = new Tesla()

Will printThis is a Tesla.

insideconstructor()Methods we can also callsuper()Call the same method in the parent class:

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

call

const myCar = new Tesla()

Now 2 console logs will be executed. The first is defined in the Car class constructor, and the second is defined in the Tesla class constructor:

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

Note that super() can only be called in the constructor, not in other methods.

And we can pass in any parameter, if the constructor accepts parameters.


More js tutorials: