DEV Community

Aishanii
Aishanii

Posted on

call(), bind() & apply() in javascript

If asked about any one of these keywords in a js interview, one thing they all have in common is they are function prototype related methods in javascript.

Every function has it's own execution context, as discussed earlier. Every function also has it's own this keyword, as introduced in ES6. We will be working around with this keyword using the methods mentioned.

call()

The call function let's us provide arguments to a function separately. Here, we are passing the value to this for the function.

I believe that it's always clearer with an example:

function chime() {
  const notif = [this.name, 'has followed you!', this.id].join(' ');
  console.log(notif);
}

const obj = {
  name: 'Joe',
  id: '@Joeisheretocomment',
};

chime.call(obj);  
Enter fullscreen mode Exit fullscreen mode

Image description
(one of those days where you do not have your pc and it becomes a default light mode day)

This is one of the use cases of call(). We use call function for constructors and objects too (find references below).

apply()

It's similar to call(), just the difference is that we pass the arguments as an array when using apply() method.

A very interesting use case of apply() that I found was while using inbuilt libraries.

array=[21,22,13,45,60,988]
console.log(Math.max(array))
Enter fullscreen mode Exit fullscreen mode

Image description
Interestingly, we can use apply here to make the Math.max function take each element of the array be considered as single and separate argument.

array=[21,22,13,45,60,988]
console.log(Math.max.apply(null,array))
Enter fullscreen mode Exit fullscreen mode

Image description

The first parameter is not used by Math.max as it doesn't need any context.

bind()

This prototyping method makes another copy of the function and is helpful to hold on to this reference.

Example :

let user = {
  follower: "JoeAgain"
};

function func() {
  alert(this.follower);
}

let funcUser = func.bind(user);
funcUser();
Enter fullscreen mode Exit fullscreen mode

In this case, we are binding a function copy with specific **this=user**.

These can be used for function currying, function binding and constructors.

Go through examples and use cases for each of them, they are so widely used, just don't get confused :D
🌟 Call & apply method
🌟this keyword and function prototyping

Top comments (0)