Home >Web Front-end >JS Tutorial >How Does `this` Work in JavaScript Function Calls and Callbacks?
Understanding This Pointers in Function Calls
In JavaScript, every function call sets a new value for this. The value assigned to this is determined by the method used to call the function.
Main Ways to Set This Pointers
There are primarily six ways to set the this pointer in JavaScript:
This in Callback Functions
Callback functions are not a unique way to set this. The calling function determines the this value when it invokes the callback.
Example Analysis
In your code snippet:
<code class="javascript">var randomFunction = function(callback) { var data = 10; callback(data); }; var obj = { initialData: 20, sumData: function(data) { var sum = this.initialData + data; console.log(sum); }, prepareRandomFunction: function() { randomFunction(this.sumData.bind(this)); } }; obj.prepareRandomFunction();</code>
Therefore, when randomFunction calls the callback, this is set to obj because of the .bind() usage in this.sumData.bind(this).
The above is the detailed content of How Does `this` Work in JavaScript Function Calls and Callbacks?. For more information, please follow other related articles on the PHP Chinese website!