What is the use of bind()
in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
bind is a function which is available in java script prototype, as the name suggest bind is used to bind your function call to the context whichever you are dealing with for eg:
Variables has local and global scopes, suppose if we have two variables with the same name, one is globally defined and another is defined inside a function closure and we want want to call that variable value which is inside the function closure, then we use this bind method. Please see the simple example below:
As mentioned,
Function.bind()
lets you specify the context that the function will execute in (that is, it lets you pass in what object thethis
keyword will resolve to in the body of the function.A couple of analogous toolkit API methods that perform a similar service:
jQuery.proxy()
Dojo.hitch()
for Javascript beginners with OOP background like me, I found this is easiest explanation to understand,
https://www.youtube.com/watch?v=GhbhD1HR5vk
You can jump to 5:00 but I would recommend watch it from beginning.
The bind() method creates a new function instance whose this value is bound to the value that was passed into bind(). For example:
Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.
Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS