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

10 / Nov / 2015 by Satyam Chaudhary 1 comments

To start with lets suppose we have a function getCount as defined below-
[code lang=”html”]function getCount(a,b,c){
return this.count + a + b + c;
}[/code]

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

1- .call():

[code lang=”html”]
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)[/code]

Output: 25

2- .apply():
[code lang=”html”]getCount.apply(obj1, [4,5,6]);
// functionName.call(‘this’ or the scope you want this function to refer, array of arguments [argument1, argument2, argument3])
[/code]
Output: 25

3- .bind():
This is slight different from above both the functions.
[code lang=”html”]
var bound = getCount.bind(obj1)
//functionName.bind(‘this’ or the scope you want this function to refer)
bound(4,5,6);
[/code]
Output: 25
Note: To explore more about bind() you can check bound function by using console.dir(bound);

Tag -

FOUND THIS USEFUL? SHARE IT

comments (1 “.call() vs .apply() vs .bind()”)

Leave a Reply

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