问题描述
在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对象内使用胖管方法?
箭头函数不是旨在在每种情况下使用只是一种较短版本的老式功能。它们不是用来替换当前函数的语法。箭头函数最常见的用例是将lambdas与词法绑定: this 相同,通常是将lambda作为回调函数传递给某些函数。
箭头函数不能用于编写对象方法,因为正如您所发现的那样,由于箭头函数假定词汇包含的这个函数上下文,对象定义中的这个是窗口或其他东西:
var foo = {
bar:()=> this.baz // lexical这是窗口或别的东西
}
在你的情况下,想要在一个对象上编写一个方法,你应该简单地使用旧的函数语法,或ES6对象字面速记中允许的版本。
有关es6邮件列表的一些争论已经有一些关于箭头函数的转换,它们具有类似的语法,但不会将这个但是,这个建议是不太好的只是语法糖,允许人们保存键入几个字符,并且不提供现有函数语法的新功能。请参阅。
$ b $早期的建议是通过使用简洁的身体减少笔划数,从而不必写入 return ,如
var foo = {
function bar()this.baz
^^^^^^^^concise body
}
但由于可执行性原因,这被拒绝。
In ES6, both of these are legal:
var chopper = { owner: 'Zed', getOwner: function() { return this.owner; } };
and, as shorthand:
var chopper = { owner: 'Zed', getOwner() { return this.owner; } }
Is it possible to use the new arrow functions as well? In trying something like
var chopper = { owner: 'John', getOwner: => { return this.owner; } };
or
var chopper = { owner: 'John', getOwner: => (this.owner) };
I get a error messages suggesting that the method does not have access to this. Is this just a syntax issue, or can you not use fat-pipe methods inside of ES6 objects?
Arrow functions are not designed to be used in every situation merely as a shorter version of old-fashioned functions. They are not intended to replace current function syntax. The most common use case for arrow functions is as short "lambdas" with "lexically bound: this, often when passing a lambda as a callback to some function.
Arrow functions cannot be used to write object methods because, as you have found, since arrow functions assume the this of the lexically enclosing function context, the this within an object definition is either the window or something else:
var foo = { bar: () => this.baz // lexical this is window or something else }
In your case, wanting to write a method on an object, you should simply use the old function syntax, or the version allowed in ES6 object literal shorthand.
There has been some debate on the es6 mailing list about a twist on arrow functions which have similar syntax but do not lexicalize this. However, this proposal was poorly received because that is mere syntax sugar, allowing people to save typing a few characters, and provides no new functionality over existing function syntax. See the topic unbound arrow functions.
An earlier proposal was to reduce stroke count by using "concise bodies", allowing you not to have to write return, as in
var foo = { function bar() this.baz ^^^^^^^^ "concise body" }
but this was rejected for parseability reasons.
这篇关于ES6对象中的方法:使用箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!