似乎 CoffeeScript 会自动返回作用域中的最后一项。我可以避免这个功能吗?
必须显式地不返回任何值,或者在函数底部留下一个计算结果为未定义的表达式:
fun = -> doSomething() return
Or:
fun = -> doSomething() undefined
这就是文档推荐的使用理解法的方法:
Be careful that you're not accidentally returning the results of the comprehension in these cases, by adding a meaningful return value — like true — or null, to the bottom of your function.
然而,你可以这样写一个包装:
voidFun = (fun) -> -> fun(arguments...) return
(请注意这里的 操作员(...))
...
在定义函数时可以这样使用:
fun = voidFun -> doSomething() doSomethingElse()
Or like this:
fun = voidFun(-> doSomething() doSomethingElse() )
longRunningFunctionWithNullReturn = -> longRunningFunction() null
似乎 CoffeeScript 中的函数必须总是返回一些东西,甚至是 null。 空函数 ->编译为 (function() {}),因此它是唯一不返回任何内容的函数。
null
->
(function() {})
只是一些有趣的东西
suppressed = _.compose Function.prototype, -> 'do your stuff'
Function.prototype本身是一个总是不返回任何值的函数。你可以使用复合函数将你的返回值导入这个黑洞,复合函数将永远不会返回任何东西。
Function.prototype
是的,以 return 作为函数的最后一行。
return
比如说,
answer = () -> 42 extrovert = (question) -> answer() introvert = (question) -> x = answer() # contemplate about the answer x return
如果你想知道咖啡编译成了什么,看看 这个。(在我的例子中,我使用了 Coffee escript reducx)