"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Posted on 2025-03-23
Browse:289

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 "

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"
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3