.call() vs .apply() vs .bind()

10 / Nov / 2015 by Satyam Chaudhary 0 comments

To start with lets suppose we have a function getCount as defined below-

function getCount(a,b,c){
  return this.count + a + b + c;
}

To provide different scope at the time of “getCount” function execution. We generally use these functions

1- .call():

var obj1 = { count: 10 };
getCount.call(obj1,4,5,6);
// functionName.call('this' or the scope you want this function 
//to refer, argument1, argument2, argument3)

Output: 25

2- .apply():

getCount.apply(obj1, [4,5,6]);
// functionName.call('this' or the scope you want this function to refer, array of arguments [argument1, argument2, argument3])

Output: 25

3- .bind():
This is slight different from above both the functions.

var bound = getCount.bind(obj1)
//functionName.bind('this' or the scope you want this function to refer)
bound(4,5,6);

Output: 25
Note: To explore more about bind() you can check bound function by using console.dir(bound);

Tag -

FOUND THIS USEFUL? SHARE IT

Leave a comment -