JavaScript 函数可以返回自身吗?
我可以编写一个返回自身的函数吗?
我正在阅读一些关于闭包的描述 - 参见示例 6 - 其中一个函数返回一个函数,所以您可以将 func()();
作为有效的 JavaScript 进行调用。
所以我想知道函数是否可以以这样的方式返回自身,您可以将其无限期地链接到自身,如下所示:
func(arg)(other_arg)()(blah);
使用参数
对象,被调用者或调用者?
Can I write a function that returns iteself?
I was reading some description on closures - see Example 6 - where a function was returning a function, so you could call func()();
as valid JavaScript.
So I was wondering could a function return itself in such a way that you could chain it to itself indefinitely like this:
func(arg)(other_arg)()(blah);
Using arguments
object, callee or caller?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以执行以下操作:
参数。 JavaScript 严格模式不支持被调用者。
https://developer.mozilla.org/en-US/docs /Web/JavaScript/Reference/Strict_mode
You can do what you want as following:
arguments.callee is not supported in JavaScript strict mode.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
甚至以上所有的排序器都是:
Even sorter that all the above is:
有一个简单的方法可以实现这一点,执行以下操作:
There is a simple way to achieve this doing the following:
也可以只返回自调用函数的参数,例如
It is also possible just to return the argument the self invokable function like
有2-3种方法。正如您所说,一种是使用
arguments.callee
。如果您正在处理未存储分配给某处变量(您知道的)的匿名函数,这可能是唯一的方法:第二种是使用函数的名称
,最后一种是使用分配给的匿名函数一个变量,但你必须知道这个变量,所以在这种情况下,我看不出为什么你不能只给函数一个名称,并使用上面的方法
它们在功能上都是相同的,但是
callee< /code> 是最简单的。
编辑:我同意 SLAks 的观点;我也无法推荐它
There are 2-3 ways. One is, as you say, is to use
arguments.callee
. It might be the only way if you're dealing with an anonymous function that's not stored assigned to a variable somewhere (that you know of):The 2nd is to use the function's name
And the last one is to use an anonymous function assigned to a variable, but you have to know the variable, so in that case I see no reason, why you can't just give the function a name, and use the method above
They're all functionally identical, but
callee
is the simplest.Edit: And I agree with SLaks; I can't recommend it either
是的。
只需
return argument.callee;
但是,这可能会导致代码非常混乱;我不推荐它。
Yes.
Just
return arguments.callee;
However, this is likely to result in very confusing code; I do not recommend it.