When working with JavaScript, knowing how to call a parent method from a child class is a handy skill that can come in useful for various programming tasks. In object-oriented programming, we often encounter scenarios where we want to access or invoke functions defined in a parent class from a child class. This process is achieved through the use of inheritance and method overriding.
One of the most straightforward ways to call a parent method from a child class in JavaScript is by using the `super` keyword. The `super` keyword is used to call corresponding methods on an object's parent class. This feature is particularly powerful when working with classes and constructor functions.
Let's dive into an example to illustrate how this works:
class Parent {
parentMethod() {
console.log("This is the parent method");
}
}
class Child extends Parent {
childMethod() {
super.parentMethod(); // Calling the parent method using super
console.log("This is the child method");
}
}
const childObj = new Child();
childObj.childMethod();
In this code snippet, we have a `Parent` class with a `parentMethod` and a `Child` class that extends `Parent`. The `Child` class contains a `childMethod` that calls the parent method using `super.parentMethod()`.
When you run this code, the output will be:
This is the parent method
This is the child method
By using the `super` keyword, the child class is able to call the parent method and also execute its own logic within the `childMethod`.
Another way to call a parent method from a child class is by directly referencing the parent class and invoking the method. This method is useful when you need to access specific functionalities from the parent class without using the `super` keyword. Here's an example:
class Parent {
parentMethod() {
console.log("This is the parent method");
}
}
class Child extends Parent {
childMethod() {
const parent = new Parent();
parent.parentMethod(); // Calling the parent method directly
console.log("This is the child method");
}
}
const childObj = new Child();
childObj.childMethod();
In this code snippet, we create an instance of the `Parent` class within the `Child` class and then call the `parentMethod` directly. This approach achieves the same result as using the `super` keyword.
Understanding how to call a parent method from a child class in JavaScript is crucial for building complex and scalable applications. By leveraging inheritance and method overriding, you can create more organized and efficient code structures that make your programs easier to maintain and extend.