What is JavaScript's bind() method ?
15 Nov 2014JavaScript’s bind()
method allows to explicitly set the value of this
to a specific object when a function is invoked.
When this
keyword is used in a method, and that method is called from a receiver object, in some cases it is bound to a different object which is not intended to resulting different outputs or even errors in the code.
Look at the Example below,
The showData method in user object behaves as expected when it is called and stored in a variable,
But gives a different output when the same method is assigned to a variable and called.
This problem may be escalated in complex JavaScript Applications.
Here showDataStud is a global variable and scope of this
becomes global scope, hence a different output.
JavaScript’s bind()
method allows what we intended to do.
bind()
is supported by most of the modern browsers including Internet Explorer 9.0, Firefox 3.0, Chrome and Opera. Since it was introduced by ECMAScript 5 it may not be compatible with older versions.