Call a Parent Method from Child Class in JavaScript | Plantpot

Call a Parent Method from Child Class in JavaScript

Web Dev
Sponsored links

In this article, I will introduce 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]);
Sponsored links

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!"