0

如何将以下 JavaScript 写入 CoffeeScript


foo.bar(function() {
    doSomething();
})(x, y);

例如,以下内容不起作用:


foo.bar ->
    doSomething()
(x, y)
4

1 回答 1

1

像这样的东西:

f ->
    ...
(x, y)

在 CoffeeScript 中有点模棱两可,因为(x, y)它本身就是一个有效的表达式。由于 和 形式的事物f(g(x))f(g)更常见f(g)(x),因此歧义被解决为两个陈述:

f -> ...

(x, y)

当解析器以您不想要的方式解决歧义时,解决方案是通过使用括号强制您想要的解释来自己解决歧义:

foo.bar(->
    doSomething()
)(x, y)

这变成了这个 JavaScript

foo.bar(function() {
  return doSomething();
})(x, y);

这可能与您尝试实现的 JavaScript 具有相同的效果,也可能不同。如果foo.bar关心其参数的返回值,那么

return doSomething();

并且只是

doSomething();

can be quite different; the implicit "return the last expression's value" in CoffeeScript can trip you up. One example would be jQuery's each which will stop iterating if the iterator function returns exactly false but will continue if the iterator returns nothing at all (i.e. undefined). If your foo.bar behaves this way then you might want to explicitly state that foo.bar's argument doesn't return anything:

foo.bar(->
    doSomething()
    return
)(x, y)

That will become this JavaScript:

foo.bar(function() {
  doSomething();
})(x, y);

and that's exactly what you're looking for.

You could also use a named function instead of an anonymous one:

pancakes = ->
    doSomething()
foo.bar(pancakes)(x, y)

You still have the possible return problem noted above (and you solve it the same way) but perhaps this structure will be easier for you to read and work with; I often refactor things this way if the anonymous function gets longer than 5-10 lines as it makes the structure easier for me to eye-ball.

于 2013-10-06T18:34:15.947 回答