ES6 对象中的箭头函数
在 ES6 中,您可以使用传统函数语法和引入的简写方法语法在对象中定义方法语言:
var chopper = { owner: 'Zed', getOwner: function() { return this.owner; } };
var chopper = { owner: 'Zed', getOwner() { return this.owner; } };
但是,您在尝试时可能会遇到限制在对象方法中使用箭头函数。例如,使用以下语法将导致错误:
var chopper = { owner: 'John', getOwner: () => { return this.owner; } };
或
var chopper = { owner: 'John', getOwner: () => (this.owner) };
说明
箭头函数具有特定特征这使得它们不适合用作对象
因此,当您在 ES6 对象中定义箭头函数时,函数中的 this将引用创建对象的上下文。例如,如果您在全局范围内定义对象 chopper,则 getOwner 中的 this 将引用全局范围,而不是 chopper 对象。
解决方案
编写ES6 中的对象方法,应该使用传统的函数语法或专门为对象设计的简写方法语法:
var chopper = { owner: 'Zed', getOwner: function() { return this.owner; } }; // or var chopper = { owner: 'Zed', getOwner() { return this.owner; } };
这些方法使用正确的 this 绑定,它引用 chopper 对象。
以上是为什么 ES6 中的对象方法不能使用箭头函数?的详细内容。更多信息请关注PHP中文网其他相关文章!