Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can we invoke the parent's method, when a child has a method with the same name in JavaScript?
When both parent and child classes have methods with the same name, JavaScript provides several ways to invoke the parent's method from the child class or externally.
Syntax
To call a parent method when overridden by a child class:
// From within child class super.methodName() // From outside using call() ParentClassName.prototype.methodName.call(childObject)
Using super Keyword (Recommended)
The super keyword is the modern way to call parent methods from within a child class:
class Parent {
constructor(value) {
this.value = value;
}
display() {
return `Parent class value: ${this.value}`;
}
}
class Child extends Parent {
constructor(value1, value2) {
super(value1);
this.value2 = value2;
}
display() {
// Call parent method using super
return `${super.display()}, Child class value: ${this.value2}`;
}
}
const childObj = new Child(10, 20);
console.log(childObj.display());
Parent class value: 10, Child class value: 20
Using call() Method
You can also invoke the parent method externally using the call() method:
class Parent {
constructor(value) {
this.value = value;
}
display() {
return `Parent class value: ${this.value}`;
}
}
class Child extends Parent {
constructor(value1, value2) {
super(value1);
this.value2 = value2;
}
display() {
return `Child class value: ${this.value2}`;
}
}
const childObj = new Child(10, 20);
// Call parent method directly
console.log("Parent method:");
console.log(Parent.prototype.display.call(childObj));
// Call child method
console.log("Child method:");
console.log(childObj.display());
Parent method: Parent class value: 10 Child method: Child class value: 20
Comparison of Methods
| Method | Usage Context | Readability | Recommendation |
|---|---|---|---|
super.methodName() |
Inside child class | High | Preferred |
ParentClass.prototype.method.call() |
Outside class or complex scenarios | Medium | Alternative |
Key Points
? Use super when calling parent methods from within the child class
? Use call() method when you need to invoke parent methods externally
? The super keyword automatically binds the correct this context
Conclusion
The super keyword is the recommended approach for calling parent methods from within child classes. Use call() method when you need external access to parent functionality.
