Home > Web Front-end > JS Tutorial > body text

What Determines the Value of `this` When a Callback Function Is Called?

Barbara Streisand
Release: 2024-11-04 03:56:02
Original
996 people have browsed it

What Determines the Value of `this` When a Callback Function Is Called?

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:

  1. Normal Function Call: this is set to the global object (e.g., window in a browser) or undefined in strict mode.
  2. Method Call: this is set to the object on which the method is called.
  3. .apply() or .call(): this is set to the object passed as the first argument.
  4. new Operator: When a function is called with new, a new object is created and this is set to that object.
  5. .bind(): Creates a new stub function where this is bound to the object passed as the first argument.
  6. 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!