JavaScript函数可以返回自己吗? [英] Can a JavaScript function return itself?

查看:251
本文介绍了JavaScript函数可以返回自己吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以写一个返回iteself的函数吗?



我正在阅读关于闭包的一些描述 - 见例6 - 函数返回一个函数,所以你可以调用 func()(); 作为有效的JavaScript。



所以我想知道函数是否可以以这种方式返回自己,以便您可以像这样无限期地链接它自己:

  func(arg)(other_arg)()(blah); 

使用参数对象,被调用者还是调用者?

解决方案

有2-3种方法。正如你所说,一个是使用 arguments.callee 。它可能是唯一的方法,如果你处理的匿名函数没有存储分配给某个变量(你知道的):

 (function(){
returns arguments.callee;
})()()()()....;

第二种是使用函数的名字

 函数namedFunc(){
return namedFunc;
}
namedFunc()()()()....;

最后一个是将一个匿名函数分配给一个变量,但您必须知道变量,所以在那种情况下,我没有看到任何理由,为什么你不能给这个函数一个名字,并且使用上面的方法

  var storedFunc = function(){
return storedFunc;
};
storedFunc()()()()....;

它们在功能上完全相同,但 callee 是最简单的。

编辑:我同意SLaks;我不能推荐它


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?

解决方案

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

(function() {
    return arguments.callee;
})()()()().... ;

The 2nd is to use the function's name

function namedFunc() {
    return namedFunc;
}
namedFunc()()()().... ;

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

var storedFunc = function() {
    return storedFunc;
};
storedFunc()()()().... ;

They're all functionally identical, but callee is the simplest.

Edit: And I agree with SLaks; I can't recommend it either

这篇关于JavaScript函数可以返回自己吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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