javascript:递归匿名函数? [英] javascript: recursive anonymous function?
问题描述
假设我有一个基本的递归函数:
Let's say I have a basic recursive function:
function recur(data) {
data = data+1;
var nothing = function() {
recur(data);
}
nothing();
}
如果我有一个匿名函数,例如...,我怎么能做到这一点
How could I do this if I have an anonymous function such as...
(function(data){
data = data+1;
var nothing = function() {
//Something here that calls the function?
}
nothing();
})();
我想要一种方法来调用调用这个函数的函数...我在某处看到过脚本(我不记得在哪里)可以告诉你被调用函数的名称,但我不能立即回想其中的任何信息.
I'd like a way to call the function that called this function... I've seen scripts somewhere (I can't remember where) that can tell you the name of a function called, but I can't recall any of that information right now.
推荐答案
您可以为函数命名,即使您将函数创建为值而不是函数声明"陈述.换句话说:
You can give the function a name, even when you're creating the function as a value and not a "function declaration" statement. In other words:
(function foo() { foo(); })();
是一个堆栈溢出的递归函数.现在,也就是说,您可能不想可能不想这样做 一般来说,因为 Javascript 的各种实现存在一些奇怪的问题.(注意 — 这是一个相当古老的评论;Kangax 的博客文章中描述的一些/许多/所有问题可能会在更现代的浏览器中得到修复.)
is a stack-blowing recursive function. Now, that said, you probably don't may not want to do this in general because there are some weird problems with various implementations of Javascript. (note — that's a fairly old comment; some/many/all of the problems described in Kangax's blog post may be fixed in more modern browsers.)
当您给出这样的名称时,该名称在函数之外是不可见的(好吧,它不应该是;这是奇怪之处之一).就像 Lisp 中的letrec".
When you give a name like that, the name is not visible outside the function (well, it's not supposed to be; that's one of the weirdnesses). It's like "letrec" in Lisp.
对于arguments.callee
,在严格"模式下是不允许的,通常被认为是一件坏事,因为它使一些优化变得困难.它也比人们想象的要慢得多.
As for arguments.callee
, that's disallowed in "strict" mode and generally is considered a bad thing, because it makes some optimizations hard. It's also much slower than one might expect.
编辑 —如果你想要一个可以调用自己的匿名"函数的效果,你可以做这样的事情(假设你将函数作为回调或类似的东西传递):
edit — If you want to have the effect of an "anonymous" function that can call itself, you can do something like this (assuming you're passing the function as a callback or something like that):
asyncThingWithCallback(params, (function() {
function recursive() {
if (timeToStop())
return whatever();
recursive(moreWork);
}
return recursive;
})());
这样做是用一个漂亮、安全、不被破坏的 IE 函数声明语句定义一个函数,创建一个名称不会污染全局命名空间的局部函数.包装器(真正匿名)函数只返回该本地函数.
What that does is define a function with a nice, safe, not-broken-in-IE function declaration statement, creating a local function whose name will not pollute the global namespace. The wrapper (truly anonymous) function just returns that local function.
这篇关于javascript:递归匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!