Understanding Call, Apply and Bind Methods in JavaScript
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.
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.
To get a grasp of "this" in JavaScript, read my post All about "this" keyword in Javascript.
Basic rules worth remembering:
- “this” always refers to an object.
- “this” refers to an object which calls the function it contains.
- In the global context “this” refers to either window object or is undefined if the ‘strict mode’ is used.
The above code will work perfectly fine, But what if we want to borrow a method?
var showFullName = name.fullName
showFullName()
Well, this won’t work as the “this” will be now assigned to the global context which doesn’t have neither the fname nor the lname property.
call() or Function.prototype.call()
Check the code sample below for call()
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 "name" object above. The rest of the parameters are the arguments to the actual function.
apply() or Function.prototype.apply()
Check the below code sample for apply()
Similarly to call() method the first parameter in apply() method sets the "this" value which is the object upon which the function is invoked. In this case it's the "name" object above. 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.
bind() or Function.prototype.bind()
Check the below code sample for bind()
In the above code sample for bind() we are returning a showFullName function with the context which will be invoked later.
The first parameter to the bind() method sets the value of "this" in the target function when the bound function is called. Please note that the value for first parameter is ignored if the bound function is constructed using the "new" operator.The rest of the parameters following the first parameter in bind() method are passed as arguments which are prepended to the arguments provided to the bound function when invoking the target function.
bind(), call() and apply() functions can make your life easier when you need to set the value of ‘this’. Hope the post was helpful.
That's all for now. Thank you for reading and I hope this post will be helpful :)







