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"
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!