为什么 coffeescript 在函数中包含 return 代码
Why coffeescript include return code in function
我想了解为什么我的 coffeescript 编译成意外的 js 代码,其中 return 语句包含在函数中。
class Smthg
...
_askAgreement: (callback) =>
@$(@aggrementModalSelector).foundation('reveal', 'open')
@$(document).on('opened.fndtn.reveal','[data-reveal]', () =>
console.log 'opened'
)
编译成
BundleToOrderActionButtonView.prototype._askAgreement = function(callback) {
this.$(this.aggrementModalSelector).foundation('reveal', 'open');
return this.$(document).on('opened.fndtn.reveal', '[data-reveal]', (function(_this) {
return function() {
return console.log('opened');
};
})(this));
};
为什么会这样:
console.log 'opened'
变成了这个:
return function() {
return console.log('opened');
};
当我期待这个时:
return console.log('opened');
由于粗箭头 (=>
),它强制嵌入 this
对象。
它允许您访问 this
就像您在函数之外一样。
使用常规箭头->
,不会生成额外函数。
coffeescript有两种写函数的方法
1) 使用单箭头语法:() ->
2) 使用粗箭头语法:() =>
使用2时,用于绑定到'this'的当前值。所以这将做的是创建一个自执行函数闭包 (IIFE http://en.wikipedia.org/wiki/Immediately-invoked_function_expression ) 将 'this' 的当前值传递给闭包。然后,您可以在闭包内的任何内容中使用 'this',这将是您所期望的。
在您的情况下,您不需要使用 'this' 值,因此您只需将函数声明更改为单箭头语法,它应该可以正常工作。
我想了解为什么我的 coffeescript 编译成意外的 js 代码,其中 return 语句包含在函数中。
class Smthg
...
_askAgreement: (callback) =>
@$(@aggrementModalSelector).foundation('reveal', 'open')
@$(document).on('opened.fndtn.reveal','[data-reveal]', () =>
console.log 'opened'
)
编译成
BundleToOrderActionButtonView.prototype._askAgreement = function(callback) {
this.$(this.aggrementModalSelector).foundation('reveal', 'open');
return this.$(document).on('opened.fndtn.reveal', '[data-reveal]', (function(_this) {
return function() {
return console.log('opened');
};
})(this));
};
为什么会这样:
console.log 'opened'
变成了这个:
return function() {
return console.log('opened');
};
当我期待这个时:
return console.log('opened');
由于粗箭头 (=>
),它强制嵌入 this
对象。
它允许您访问 this
就像您在函数之外一样。
使用常规箭头->
,不会生成额外函数。
coffeescript有两种写函数的方法
1) 使用单箭头语法:() ->
2) 使用粗箭头语法:() =>
使用2时,用于绑定到'this'的当前值。所以这将做的是创建一个自执行函数闭包 (IIFE http://en.wikipedia.org/wiki/Immediately-invoked_function_expression ) 将 'this' 的当前值传递给闭包。然后,您可以在闭包内的任何内容中使用 'this',这将是您所期望的。
在您的情况下,您不需要使用 'this' 值,因此您只需将函数声明更改为单箭头语法,它应该可以正常工作。