When to use call, apply and bind in JavaScript

Here in this post I will try to explain when to use call(), apply() and bind() in JavaScript/EcmaScript.  As we know Functions are first-class objects in JavaScript, because they can have properties, methods/fuctions and scope just like any other object. So what is so special about it? It can be called from other objects and scope/this can be passed to it.

We will see from the examples

function printBye(message1, message2){
console.log(message1 + " " + this.name + " "+ message2);

printBye("Bye", "Never come again");//Bye undefined Never come again

var par01 = { name:"John" };
var msgArray = ["Bye", "Never come again..."];

printBye.call(par01, "Bye", "Never come again...");//Bye John Never come again...
printBye.call(par01, msgArray);//Bye,Never come again... John undefined
//so call() doesn't work with array and it is better with comma seperated parameters 

//printBye.apply(par01, "Bye", "Never come again...");//Error
printBye.apply(par01, msgArray);//Bye John Never come again...

var func1 = printBye.bind(par01, "Bye", "Never come again...");
func1();//Bye John Never come again...

var func2 = printBye.bind(par01, msgArray);
func2();//Bye,Never come again... John undefined
//so bind() doesn't work with array and it is better with comma seperated parameters

In the above sample code the function printBye() which has “this.name” which is part of the printBye() in order pass the “this” we can use any of the methods call() or apply() or bind() and all have their own behaviours.


Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.