javascript:递归匿名函数? [英] javascript: recursive anonymous function?

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

问题描述

假设我有一个基本的递归函数:

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实现存在一些奇怪的问题。 ( note —这是一个相当古老的评论; 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屋!

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