You can use call()/apply() to invoke the function immediately.
The only difference of apply() with the call() method is that the second parameter of the apply() method accepts the arguments to the actual function as an array
You 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.
//1. call() or Function.prototype.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
//The first parameter in call() method sets the "this" value, which is the object, on which the function is invoked upon. In this case, it's the "obj" object above.
//The rest of the parameters are the arguments to the actual function.
//2. apply() or Function.prototype.apply()
var obj = {name:"Niladri"};
var greeting = function(a,b,c){
return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};
// array of arguments to the actual function
var args = ["Newtown","KOLKATA","WB"];
console.log("Output using .apply() below ")
console.log(greeting.apply(obj,args));
/* The output will be
Output using .apply() below
welcome Niladri to Newtown KOLKATA in WB */
//3. bind() or Function.prototype.bind()
var obj = {name:"Niladri"};
var greeting = function(a,b,c){
return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};
//creates a bound function that has same body and parameters
var bound = greeting.bind(obj);
console.dir(bound); ///returns a function
console.log(bound("Newtown","KOLKATA","WB")); //call the bound function
//You 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.