
In this post, we will be discussing the difference between call(), apply(), and bind() methods of JavaScript functions with simple examples. As functions are also Objects in JavaScript, these 3 methods are used to control the invocation of the function. call() and apply() were introduced in ECMAScript 3 while bind() was added as part of ECMAScript 5.
Uses
We can use call()/apply() to invoke the function immediately. bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function. So bind() can be used when the function needs to be called later in certain events when it's useful.
To get a grasp of "this" in JavaScript, read Understanding "this" in javascript and also Difference between scope and context in javascript.
call() or Function.prototype.call()
Check the code sample below for call(),
- //Demo with javascript .call()
- var obj = {name:"Niladri"};
- var greeting = function(a,b,c){
- return "welcome "+this.name+" to "+a+" "+b+" in "+c;
- };
- console.log(greeting.call(obj,"Newtown","KOLKATA","WB"));
- // returns output as welcome Niladri to Newtown KOLKATA in WB


Join the conversation! Your thoughts help the community grow.