Why is JavaScript bind() necessary?
The value of this is determined by how a function is called. If it is you who calls the function then there is usually no need to use .bind, since you have control over how to call the function, and therefore its this value.
However, often it is not you who calls the function. Functions are passed to other functions as callbacks and event handlers. They are called by other code and you have no control over how the function is called, and therefore cannot control what this will refer to.
If your function requires this to be set to a specific value and you are not the one calling the function, you need to .bind the function to a specific this value.
In other words: .bind allows you to set the value of this without calling the function now.
Here is comparison of referring to/calling functions:
+-------------------+-------------------+
| | |
| time of | time of |
|function execution | this binding |
| | |
+-------------------+-------------------+-------------------+
| | | |
| function object | future | future |
| f | | |
| | | |
+-------------------+-------------------+-------------------+
| | | |
| function call | now | now |
| f() | | |
| | | |
+-------------------+-------------------+-------------------+
| | | |
| f.call() | now | now |
| f.apply() | | |
| | | |
+-------------------+-------------------+-------------------+
| | | |
| f.bind() | future | now |
| | | |
+-------------------+-------------------+-------------------+
I'm also wondering why example 3 solves the issue and the difference between example 2 and 3.
Example 1/2 and 3 couldn't be more different. storeMyName and storeMyName2 contain functions, which are called in the future, whereas storeMyName3 contains the result of calling myName.getName() at that moment.
Further reading material:
thisis determined dynamically, unless it is a bound or an arrow function. Not sure what else you want to know expect learning about howthisworks.storeMyNameandstoreMyName2contain functions whereasstoreMyName3contains the result of callingmyName.getName(). Big difference. I made this comparison between ways of calling a function and.bind: twitter.com/fkling42/status/736228742008176640 . Maybe it helps somehow.thisin JS for me: rainsoft.io/gentle-explanation-of-this-in-javascript