【发布时间】:2025-12-15 12:55:02
【问题描述】:
我需要在 CoffeeScript 中进行一些高级数组排序,我遇到了 thenBy.js 微型库,它完全符合我的需求。它是用 JavaScript 编写的,所以我将它翻译成 CoffeeScript,以便我可以在我的 .coffee 文件中内联使用它,但我在翻译时遇到了一些问题。这不起作用:
firstBy = ->
# mixin for the `thenBy` property
extend = (f) ->
f.thenBy = tb
return f
# adds a secondary compare function to the target function (`this` context)
#which is applied in case the first one returns 0 (equal)
#returns a new compare function, which has a `thenBy` method as well
tb = (y) ->
x = this
return extend((a, b) ->
return x(a, b) or y(a, b)
)
return extend
但是,如果我用括号括起来并放在尾随括号上,它确实有效:
### Notice the starting paren
firstBy = (->
# mixin for the `thenBy` property
extend = (f) ->
f.thenBy = tb
return f
# adds a secondary compare function to the target function (`this` context)
#which is applied in case the first one returns 0 (equal)
#returns a new compare function, which has a `thenBy` method as well
tb = (y) ->
x = this
return extend((a, b) ->
return x(a, b) or y(a, b)
)
return extend
)() ### <- Notice the ending parens
我无法理解为什么将这些尾随括号放在事物上会使其工作。我知道我有一个匿名函数,然后我用这些括号 (see this answer) 调用它,但为什么会这样呢?
【问题讨论】:
-
两个版本都可以编译成 JS 看看有什么不同吗?
-
是的。它们都编译得很好,括号是两者在输出 JS 和输入中的唯一区别。这真的只是我不明白这个聪明的小 sn-p 是如何实际工作的。为什么在定义它时必须调用它才能使其工作?
-
您能否尝试仅在第一个示例中使用
=>而不是->用于extend和tb,让我知道这是否适合您?