在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)
};
我收到一条错误消息,提示该方法无权访问this
。这仅仅是语法问题,还是不能在ES6对象中使用胖管道方法?
箭头函数并非旨在在所有情况下都用作老式函数的简化版本。它们不打算使用function
关键字替换函数语法。箭头函数最常见的用例是不重新定义的短“ lambdas” this
,通常在将函数作为回调传递给某些函数时使用。
箭头函数不能用于编写对象方法,因为,正如您所发现的,由于箭头函数this
在词法包围的上下文上方闭合,this
因此箭头内的in是定义对象的当前位置。就是说:
// Whatever `this` is here...
var chopper = {
owner: 'Zed',
getOwner: () => {
return this.owner; // ...is what `this` is here.
}
};
对于您的情况,要在对象上编写方法,应仅使用传统function
语法或ES6中引入的方法语法:
var chopper = {
owner: 'Zed',
getOwner: function() {
return this.owner;
}
};
// or
var chopper = {
owner: 'Zed',
getOwner() {
return this.owner;
}
};
(它们之间有细微的差别,但是只有在不使用或复制到另一个对象super
中时getOwner
,它们才重要getOwner
。)
在es6邮件列表上有一些关于箭头功能的争论,它们具有相似的语法,但具有自己的语法this
。但是,该建议很少得到接受,因为这仅仅是语法糖,使人们可以省去键入几个字符,并且不提供比现有函数语法更多的新功能。请参阅主题未绑定箭头功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句