Immediately invoked named functions

ぃ、小莉子 提交于 2019-12-22 08:17:15

问题


A friend of mine posed an interesting question to me today about how to write immediately invoked named functions in CoffeeScript without hoisting the function variable to the outer scope.

In JavaScript:

(function factorial(n) { return n <= 1 ? 1 : n * factorial(n-1); })(5);

The best I could come up with in CoffeeScript:

do -> do factorial = (n = 5) ->
    if n <= 1 then 1 else n * factorial(n-1)

looks a bit awkward. Is there a better way to do this?


回答1:


You can’t. CoffeeScript doesn’t support this kind of thing at all, except via inline JavaScript:

result = `(function factorial(n) {`
return if n <= 1 then 1 else n * factorial(n-1)
`})(5)`

(No indenting allowed, either.) CoffeeScript will insert some semicolons for you, too, so no using it in expression context.

Then again…

-> if n <= 1 then 1 else n * arguments.callee n-1

(don’t do that)



来源:https://stackoverflow.com/questions/22029514/immediately-invoked-named-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!