函数表达式可以转换为 lambda 表达式
Function expression may be converted to lambda expression
如果我有这样的片段
module MyModule{
export var myfunc = function() {
}
}
然后 ReSharper 建议转换为
module MyModule{
export var myfunc = () => {
}
}
但是当函数使用 this
时它不起作用
module MyModule{
export var myfunc = function(){
var x = $(this);
}
}
为什么在使用 this
时转换不起作用?
(如果你想知道为什么我在模块中使用 this
,那是因为这个方法是一个事件处理程序)
箭头函数是隐式设置的,因此 this
是箭头函数实例化范围内的任何内容。就好像你写道:
var myfunc = () => { ... } .bind(this);
我认为这背后的概念是这样的回调确实希望从外部上下文访问 this
值。如您所见,有时他们不会。
如果我有这样的片段
module MyModule{
export var myfunc = function() {
}
}
然后 ReSharper 建议转换为
module MyModule{
export var myfunc = () => {
}
}
但是当函数使用 this
module MyModule{
export var myfunc = function(){
var x = $(this);
}
}
为什么在使用 this
时转换不起作用?
(如果你想知道为什么我在模块中使用 this
,那是因为这个方法是一个事件处理程序)
箭头函数是隐式设置的,因此 this
是箭头函数实例化范围内的任何内容。就好像你写道:
var myfunc = () => { ... } .bind(this);
我认为这背后的概念是这样的回调确实希望从外部上下文访问 this
值。如您所见,有时他们不会。