Arrow Functions in ES6 Objects
In ES6, you can define methods in objects using both the traditional function syntax and the shorthand method syntax introduced in the language:
var chopper = { owner: 'Zed', getOwner: function() { return this.owner; } };
var chopper = { owner: 'Zed', getOwner() { return this.owner; } };
However, you may encounter limitations when attempting to use arrow functions in object methods. For instance, using the following syntax will result in an error:
var chopper = { owner: 'John', getOwner: () => { return this.owner; } };
or
var chopper = { owner: 'John', getOwner: () => (this.owner) };
Explanation
Arrow functions have specific characteristics that make them unsuitable for use as object methods.
Therefore, when you define an arrow function within an ES6 object, this within the function will refer to the context where the object was created. For example, if you define the object chopper within a global scope, this inside getOwner will refer to the global scope, not the chopper object.
Solution
To write object methods in ES6, you should use traditional function syntax or the shorthand method syntax specifically designed for objects:
var chopper = { owner: 'Zed', getOwner: function() { return this.owner; } }; // or var chopper = { owner: 'Zed', getOwner() { return this.owner; } };
These methods use the correct this binding, which refers to the chopper object.
The above is the detailed content of Why Can't I Use Arrow Functions for Object Methods in ES6?. For more information, please follow other related articles on the PHP Chinese website!