Home >Web Front-end >JS Tutorial >How Does the 'this' Keyword Differ Between Arrow Functions and Regular Functions in JavaScript?

How Does the 'this' Keyword Differ Between Arrow Functions and Regular Functions in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-10 02:14:13636browse

How Does the

Arrow Functions and Context-less "This"

In ES6, arrow functions provide a concise syntax for function declaration. However, one key difference between arrow functions and traditional functions is their handling of the "this" keyword.

When you use an arrow function inside an object as shown in the given code:

var person = {
  name: "jason",

  shout: () => console.log("my name is ", this.name)
}

The "this" keyword within the arrow function does not refer to the "person" object. Instead, it points to the scope where the arrow function was created, which in this case is the global scope. Therefore, when calling "person.shout()", it logs "my name is" without the "jason" property.

To resolve this issue, you can use regular function syntax instead of an arrow function:

var person = {
  name: "jason",

  shout: function() {
    console.log("my name is ", this.name)
  }
}

In regular functions, "this" refers to the object that owns the function. Therefore, it will correctly output "my name is jason" when called.

Alternatively, you can take advantage of the ES6 method declaration syntax, which is similar to the arrow function syntax:

var person = {
  name: "jason",

  shout() {
    console.log("my name is ", this.name)
  }
}

With this syntax, the function declaration omits the colon (:) and the "function" keyword. However, it still uses the regular function declaration syntax, ensuring that "this" bound to the object.

The above is the detailed content of How Does the 'this' Keyword Differ Between Arrow Functions and Regular Functions in JavaScript?. 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