Home >Web Front-end >JS Tutorial >How Does `this` Work in JavaScript Function Calls and Callbacks?

How Does `this` Work in JavaScript Function Calls and Callbacks?

DDD
DDDOriginal
2024-11-03 15:42:30369browse

How Does `this` Work in JavaScript Function Calls and Callbacks?

When This Pointers Are Set in JavaScript

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:

  • Normal Function Call: Defaults to the global object (e.g., window) or undefined (in strict mode).
  • Method Call: Points to the object owning the method.
  • **.apply() or .call(): Sets this according to the argument passed.
  • Using new: Creates a new object and sets this to it.
  • **.bind(): Returns a new function with a custom this value, using .apply() internally.
  • ES6 Fat Arrow Functions: Binds the current lexical this value (cannot be overridden).

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>
  • obj.prepareRandomFunction() uses a method call, setting this to obj.
  • randomFunction(this.sumData.bind(this)) uses .bind(), which binds the current this value (i.e., obj) to the callback function returned.

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!

Statement:
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