Immediately invoked named functions

2019-05-07 06:27发布

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条回答
ゆ 、 Hurt°
2楼-- · 2019-05-07 07:14

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)

查看更多
登录 后发表回答