0

CoffeeScript 有一个方便的do语句来保存闭包中的变量。但是如何保留thiswith的属性do?这似乎总是失败。

示例:在类方法中,我想使用 jQuery 将事件处理程序附加到 HTML 元素。处理程序应使用参数调用同一类的另一个方法。现在,如果我写:

foo = getBar()
$('div').click -> @handler foo

这显然不起作用,因为该函数将在没有名为 的方法的不同上下文中执行handler。但是,如果我使用do并写下这个:

foo = getBar()
do (@handler, foo) ->
  $('div').click -> @handler foo

这也将失败,因为 @handler 转换为 this.handler 没有通过闭包。解决这个问题的优雅方法是什么?

4

1 回答 1

1

尝试使用粗箭头(等号)

foo = getBar()
$('div').click => @handler foo

或者,在回调之前获取对处理程序的引用。

cbHandler = @handler
foo = getBar()
$('div').click -> cbHandler foo
于 2013-10-11T19:10:09.817 回答