Brief Note on Call, Bind and Apply in JavaScript
This could be one of my micro blog post that i have written since writing blog. Anyways let me not waste any of your time by writing something that is not relevant to you. If you’re well-known to JavaScript then i’m sure that you know ‘this’ keyword. The ‘this’ keyword in JavaScript behaves differently compared to other programming languages. This causes a lot of confusion for developers like you and me. In other object-oriented programming languages, the this keyword always refers to the current instance of the class. Whereas in JavaScript, the value of this depends on how a function is called.
We use call, bind and apply methods to set the this keyword independent of how the function is called. This is especially useful for the callbacks and this are 3 methods available to all functions. They let you set the ‘this’ keyword to any object you pass in. The first argument to all of them is always the object you want the ‘this’ to become.
So what are the difference between them?
Bind: The bind method returns another function, with the ‘this’ already binded to the object you passed in. So in the first example, you can see we call the getName function, we bind the themesfinity object to it, and then we save the function returned to “getNameBind”. We then invoke that function and get our output.
Call: The call method, contrary to the bind method, executes our function immediately, with the this binded to the object you pass on the first argument. In the 2nd example you can see we call the getName function with the call method, we bind the themesfinity object to it, and then we pass the arguments 2 and 4. The function gets executed immediately, so we get our output on the console.
Apply: The apply method, is pretty much the same as the call. It executes the function immediately too, but the exception is that it only accept an array as the 2nd argument. So you can see we call the getName function with apply, we bind the ‘this’ to the themesfinity object, and then we pass the array as an argument.
Comments
No comment yet.