为什么coffeescript在函数中包含返回代码

时间:2015-01-13 16:20:17

标签: coffeescript

我试图理解为什么我的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');

2 个答案:

答案 0 :(得分:2)

有两种方法可以在coffeescript中编写函数

1)使用单箭头语法:() - >

2)使用胖箭头语法:()=>

使用2时,它用于将其绑定到'this'的当前值。那么这将做的是创建一个自动执行的函数闭包(IIFE http://en.wikipedia.org/wiki/Immediately-invoked_function_expression),将当前值'this'传递给闭包。然后,您可以在闭包内的任何内容中使用“this”,这将是您所期望的。

在您的情况下,您不需要使用'this'值,因此您可以将函数声明更改为单箭头语法,它应该可以正常工作。

答案 1 :(得分:1)

由于胖箭头(=>),强制嵌入this对象。

它允许您访问this,就像您在函数之外一样。

使用常规箭头->,它不会生成额外的功能。