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
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3