如何用CoffeeScript写$(this)?

Tyc*_*hio 0 javascript this coffeescript

我的CoffeeScript代码:

a = (argu='.a') =>
    $(argu).on 'click', () =>
        $(this)
Run Code Online (Sandbox Code Playgroud)

编译为Javascript:

var a,
    _this = this;

a = function(argu) {
    if (argu == null) {
        argu = '.a';
    }
    return $(argu).on('click', function() {
        return $(_this);
    });
};
Run Code Online (Sandbox Code Playgroud)

我希望那this是$(争论)或$('.a')而不是_this.

如何写'这个'可以参考$(争论)?

Mat*_*all 5

内部胖箭头(=>)是你_this在点击处理程序中结束的原因.如果你使用普通箭头,你会得到你想要的:

a = (argu='.a') =>
    $(argu).on 'click', -> # you can also remove the empty ()s
        $(this)
Run Code Online (Sandbox Code Playgroud)

编译成

var a,
  _this = this;

a = function(argu) {
  if (argu == null) {
    argu = '.a';
  }
  return $(argu).on('click', function() {
    return $(this);
  });
};
Run Code Online (Sandbox Code Playgroud)

这是因为

胖箭头=>既可以用来定义一个函数,也可以在现场将它绑定到当前值.

而"瘦"箭头定义了一个函数,但没有将它绑定到特定的上下文.


现在,如果你真的想要this在回调中$(argu)- 注意这变成了非惯用的jQuery,因为this在回调中不会引用被点击的元素 - 你可以执行以下操作:

a = (argu='.a') =>
    $argu = $(argu)
    $argu.on 'click', (-> $(this)).bind($argu)
Run Code Online (Sandbox Code Playgroud)

要明确:我不建议这样做.