我需要在CoffeeScript中進行一些高級的數組排序,並且我遇到了完全符合我的需求的thenBy.js微庫。它是用JavaScript編寫的,所以我將它翻譯成CoffeeScript,以便我可以在我的.coffee文件中內聯使用它,並且我在翻譯時遇到了一些問題。這不起作用:將JavaScript中的thenBy.js翻譯爲CoffeeScript的問題
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與兩個版本,並看到不同之處? – rdodev
是的。它們都編譯得很好,而且在輸出JS和輸入之間,只有兩個不同。這真的只是我的一個問題,並不瞭解這個聰明的小片段是如何實際完成其工作的。爲什麼在定義它的時候需要調用它才能使其正常工作? – mattmc3
只有在第一個例子中,你可以嘗試使用'=>'而不是' - >'來代替'extend'和'tb',並且讓我知道它是否適合你? – rdodev