How can we invoke the parent's method, when a child has a method with the same name in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

In order to call the parent method when both parent and child have the same method name and signature.

You can use the below syntax −

console.log(yourParentClassName.prototype.yourMethodName.call(yourChildObjectName));

Example

class Super {
   constructor(value) {
      this.value = value;
   }
   display() {
      return `The Parent class value is= ${this.value}`;
   }
}
class Child extends Super {
   constructor(value1, value2) {
      super(value1);
      this.value2 = value2;
   }
   display() {
      return `${super.display()}, The Child Class value2
      is=${this.value2}`;
   }
}
var childObject = new Child(10, 20);
console.log("Calling the parent method display()=")
console.log(Super.prototype.display.call(childObject));
console.log("Calling the child method display()=");
console.log(childObject.display());

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo192.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo192.js
Calling the parent method display()= The Parent class value is= 10
Calling the child method display()= The Parent class value is= 10, The Child Class value2 is=20
raja
Published on 14-Sep-2020 08:31:11
Advertisements