DEV Community

Vamshi Krishna
Vamshi Krishna

Posted on

Understanding call, apply, and bind in JavaScript with Simple Examples

Understanding call, apply, and bind in JavaScript with Simple Examples

When working with JavaScript, you might come across three powerful methods: call, apply, and bind. These methods are used to control the value of this in functions, making it easier to work with objects. Let's break down each method with simple examples to understand how they work.

1. call Method

The call method allows you to invoke a function with a specific this value and pass arguments one by one.

const person = {
  name: 'Alice',
  greet: function(greeting) {
    console.log(`${greeting}, my name is ${this.name}`);
  }
};

const anotherPerson = { name: 'Bob' };

person.greet.call(anotherPerson, 'Hello');
// Output: "Hello, my name is Bob"
Enter fullscreen mode Exit fullscreen mode

In this example, call changes the this value from person to anotherPerson, so the greet function prints "Hello, my name is Bob".

2. apply Method

The apply method is similar to call, but it takes arguments as an array instead of one by one.

const person = {
  name: 'Alice',
  greet: function(greeting, punctuation) {
    console.log(`${greeting}, my name is ${this.name}${punctuation}`);
  }
};

const anotherPerson = { name: 'Charlie' };

person.greet.apply(anotherPerson, ['Hi', '!']);
// Output: "Hi, my name is Charlie!"
Enter fullscreen mode Exit fullscreen mode

Here, apply also changes the this value to anotherPerson and allows you to pass multiple arguments as an array.

3. bind Method

The bind method doesn't call the function immediately. Instead, it returns a new function with a bound this value that you can call later.

const person = {
  name: 'Alice',
  greet: function() {
    console.log(`Hi, my name is ${this.name}`);
  }
};

const anotherPerson = { name: 'Diana' };

const greetDiana = person.greet.bind(anotherPerson);

greetDiana();
// Output: "Hi, my name is Diana"
Enter fullscreen mode Exit fullscreen mode

In this example, bind creates a new function greetDiana with this bound to anotherPerson. When you call greetDiana, it prints "Hi, my name is Diana".

Summary

  • call: Immediately invokes the function with a specific this value and arguments passed one by one.
  • apply: Immediately invokes the function with a specific this value and arguments passed as an array.
  • bind: Returns a new function with a specific this value, which you can call later.

These methods are handy when you need to borrow methods from one object to use with another or when you want more control over the this value in your functions.


Top comments (0)