When this Argues: Understanding 'this' in Callback Functions
In JavaScript, the value of this in a function call is determined by the context in which the function is executed. When passing this as an argument, however, the rules can get complicated.
Specifically, the following scenario arises: when a callback function is passed as an argument, why doesn't this get set to the function that calls the callback?
Understanding the Hierarchy of 'this'
To understand why this is set where it is, we need to consider the hierarchy of function calls:
However, before randomFunction calls the callback, it uses this.sumData.bind(this) to create a new function (rule #5). This new function calls the original callback function, but now with this bound to obj (the argument passed to bind).
Implications for Callback Functions
When passing a method as a callback, it's crucial to understand that it won't be called as obj.method(). This means this will not have the correct value inside the callback function. To work around this issue, you can use bind() to set the value of this within the callback.
Other Useful Notes
The above is the detailed content of Why Doesn\'t \'this\' Refer to the Calling Function in JavaScript Callbacks?. For more information, please follow other related articles on the PHP Chinese website!