Call Child Method From Parent

Call Child Method from Parent

When working with JavaScript, you may come across a situation where you need to call a method defined in a child class from its parent class. This can be achieved using various techniques. In this blog post, we will explore three different solutions to this problem.

Solution 1: Using the call() Method

The call() method allows you to call a function with a given this value and arguments provided individually. By using call() in the parent class, you can invoke the child method and pass the appropriate context.


class Parent {
  callChildMethod() {
    Child.prototype.childMethod.call(this);
  }
}

class Child {
  childMethod() {
    console.log("Child method called from the parent");
  }
}

const parent = new Parent();
parent.callChildMethod();

Output:

Child method called from the parent

Solution 2: Using the apply() Method

Similar to call(), the apply() method allows you to call a function with a given this value and arguments provided as an array. This approach is useful when you have a dynamic number of arguments.


class Parent {
  callChildMethod() {
    Child.prototype.childMethod.apply(this);
  }
}

class Child {
  childMethod() {
    console.log("Child method called from the parent");
  }
}

const parent = new Parent();
parent.callChildMethod();

Output:

Child method called from the parent

Solution 3: Using the super Keyword

If you are using ES6 classes, you can utilize the super keyword to call methods defined in the parent class from the child class. This approach allows for better code organization and readability.


class Parent {
  callChildMethod() {
    this.childMethod();
  }
}

class Child extends Parent {
  childMethod() {
    console.log("Child method called from the parent");
  }
}

const child = new Child();
child.callChildMethod();

Output:

Child method called from the parent

These are three different ways to call a child method from a parent class in JavaScript. Choose the approach that best fits your requirements and coding style. Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *