When the Value of this Is Set
In JavaScript, the value of this is determined by how a function is called. There are six primary ways to set this:
-
Normal Function Call: this is set to the global object (e.g., window in a browser) or undefined in strict mode.
-
Method Call: this is set to the object on which the method is called.
-
.apply() or .call(): this is set to the object passed as the first argument.
-
new Operator: When a function is called with new, a new object is created and this is set to that object.
-
.bind(): Creates a new stub function where this is bound to the object passed as the first argument.
-
ES6 Fat Arrow Function: this is bound to the lexical value of the enclosing scope.
The Case of Callback Functions
In your example:
<code class="javascript">randomFunction(this.sumData.bind(this));</code>
Copy after login
- this.sumData.bind(this) uses .bind() to bind this to the obj object.
- Consequently, when randomFunction calls the callback function, this is set to obj because of the .bind().
- If you were to swap this.sumData.bind(this) with callback(data), this inside randomFunction would be set to the global object (or undefined in strict mode).
This is because callback is passed as a reference to this.sumData.bind(this), but when randomFunction calls callback, it sets this according to the rules of a normal function call.
The above is the detailed content of What Determines the Value of `this` When a Callback Function Is Called?. For more information, please follow other related articles on the PHP Chinese website!