How to Delegate in JavaScript?

Estimated read time 2 min read

Delegation is a design pattern in JavaScript that involves assigning the responsibility for a task to another object, rather than handling the task directly. This can be useful for organizing code and avoiding tight coupling between objects.

In JavaScript, delegation can be implemented using the prototype chain. The prototype chain allows objects to inherit properties and methods from other objects. When a property or method is not found on an object, JavaScript looks for it on the object’s prototype, and then on the prototype’s prototype, and so on, until it is found or the end of the prototype chain is reached.

Here’s an example of delegation using the prototype chain:

// Parent object
const parent = {
  name: "Parent",
  greet() {
    console.log(`Hello, I'm ${this.name}`);
  }
};

// Child object
const child = Object.create(parent);
child.name = "Child";

// Call the greet method on the child object
child.greet(); // "Hello, I'm Child"

In this example, we have a parent object with a name property and a greet method. We then create a child object using Object.create(parent). This sets the child object’s prototype to parent, so it inherits the name and greet properties from the parent object. We then set the child object’s name property to “Child”.

When we call the greet method on the child object, JavaScript first looks for the greet method on the child object itself, but it does not find it. It then looks for the greet method on the parent object, and it finds it. Finally, it calls the greet method on the parent object with the this keyword set to the child object, which outputs “Hello, I’m Child”.

This is an example of delegation, where the child object delegates the responsibility of the greet method to the parent object.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply