Call a Parent Method from Child Class in JavaScript

02/05/2022

Contents

In this article, you will learn how to call a parent method from child class in JavaScript.

The super keyword

The super keyword can be used to call an object’s parent functions.

It takes two steps to call the parent class (superclass) with the super keyword.
First, extend the parent class with extends.
Then use the super keyword to call the parent class.

The syntax is below.

super([arguments]);
super.functionOnParent([arguments]);

Sample Code

 class Animal {
 constructor(name){
  this.name = name
 }
 bark() {
  console.log("grrr") 
 }
}

// Inherit Animal class
class Dog extends Animal {
 constructor(name){
 // Call the parameter of the parent class
  super(name)
 }

 bark() {
 // Call the bark method of the parent class
  super.bark()
  console.log("baw baw!")
 }
}

// Call the Animal class
var animal = new Animal("Lion")
console.log(animal.name) // => "Lion"
animal.bark() // => "grrr"

var dog = new Dog("Leo")
console.log(dog.name) // => "Leo"
dog.bark() 
// => "grrr" ,"baw baw!"