DEV Community

Abhishek Patel
Abhishek Patel

Posted on

How And When to use bind, call, and apply in JavaScript

Call
call quite simply lets you substitute a this context when you invoke a function. Calling the .call() method on a function, will immediately invoke that function.
let Person = {
name: "Abhishek Patel",
showname : function(){
return this.name;
}
};
let changename = {
name: "Abhishek"
};
Person.showname; // "Abhishek Patel"
Person.showname.call(changename); // "Abhishek"
When to use call

When you are dealing with an array-like object and want to call an array method.

Apply
The apply() method is used to write methods, which can be used on different objects

let name={
firstname:"Abhishek",
lastname:"Patel
}
let printFullname=function(home,state)
{
console.log(this.firstname+" "+this.lastname+"from"+hometown+","+state
}
printFullname.apply(name,"[Sonepur","Bihar"]) //"Abhishek Patel from Sonepur ,Bihar
so in above function "this" will point to "name" object
we can also apply call function in this way
printFullname.apply(name,"Sonepur","Bihar")

When to use apply

A common use case for apply was to call functions that couldn’t be passed an array of arguments. For example, if you had an array of numbers: let nums = [1,2,3] and you wanted to find the smallest number. You couldn’t just call Math.min(nums) you would instead have to call Math.min.apply(null,nums) to get a minimum.

Bind
Bind creates a new function that will force the "this" inside the function to be the parameter passed to bind().

let name={
firstname:"Abhishek",
lastname:"Patel
}
let printFullname=function(home,state)
{
console.log(this.firstname+" "+this.lastname+"from"+hometown+","+state
}
let printmyname=printFullname.bind(name,"Sonepur","Bihar")
printmyname() //"Abhishek Patel from Sonepur ,Bihar
So,bind will force "this" to point at "name object
When to use
Async stuff
A very common front-end use case for bind is for anything that will happen asynchronously. For example in a callback that needs access to the original this context. This is especially handy in component based frameworks like React.

Further Reading
Call()-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
Apply()-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
Bind()-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Top comments (0)