Home > Web Front-end > JS Tutorial > Arrow Functions vs. Method Declarations in ES6: Why Doesn't `this` Work as Expected in Arrow Functions?

Arrow Functions vs. Method Declarations in ES6: Why Doesn't `this` Work as Expected in Arrow Functions?

Linda Hamilton
Release: 2024-12-15 13:41:09
Original
292 people have browsed it

Arrow Functions vs. Method Declarations in ES6: Why Doesn't `this` Work as Expected in Arrow Functions?

Arrow Functions vs. Method Declarations in ES6

When delving into ES6, you may encounter the following issue:

var person = {
  name: "jason",

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

person.shout(); // Prints "my name is "
Copy after login

The intention is to have the function access the name property within the person object. However, the console only prints "my name is."

Explanation:

This behavior arises from the distinct nature of arrow functions in ES6. Arrow functions, unlike traditional function declarations, do not bind the this keyword. Instead, they inherit the this binding from their surrounding scope, which, in this case, is the global scope.

Solution:

To address this issue, you can use the ES6 method declaration pattern, which preserves the desired binding of this:

var person = {
  name: "jason",

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

person.shout(); // Prints "my name is jason"
Copy after login

The above is the detailed content of Arrow Functions vs. Method Declarations in ES6: Why Doesn't `this` Work as Expected in Arrow Functions?. 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