立即调用命名函数 [英] Immediately invoked named functions

查看:103
本文介绍了立即调用命名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个朋友今天向我提出一个有趣的问题,关于如何在CoffeeScript中立即调用命名函数,而不将函数变量提升到外部范围。

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.

JavaScript:

In JavaScript:

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

我在CoffeeScript中最好的想法:

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?

推荐答案

你不能。 CoffeeScript不支持这种事情

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)`

(不允许缩进)。CoffeeScript将为你插入一些分号,所以在表达式上下文中不使用它。

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

/ p>

Then again…

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

这样做)

这篇关于立即调用命名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆