2012-05-07 45 views
1

我已经搜索了JavaScript中的递归调用,但我想做一个“未命名”函数的递归调用。未命名函数的递归函数调用JavaScript

结果我发现使用谷歌是这样

function foo() { 
    setTimeout("foo()",0); 
} 

,但我想打的东西,会是这样:

(function() { alert(this.function) })() 

这可能吗?

+0

内可用的是有一些原因,你不想给你的函数的名称? –

回答

5

如果您不在strict mode中,则可以使用arguments.callee获取功能对象,请参阅MDN文档。例如

(function() { 
    console.log(typeof arguments.callee); // "function" 
    arguments.callee(); // call to itself 
})(); 

但作为建议也有,你应该避免这种说法,并给予一个标识符的功能,像这样

(function foo() { 
    foo(); // call to itself 
})(); 
0

据我所知,你不能。你必须有一个引用(名称或变量)来回叫。

虽然有arguments.callee但它气馁

注意:应避免使用arguments.callee的(),只是给每个功能(表达)的名称。

0

基本上你正在寻找一种叫做Y-Combinator的东西(或者说维基百科把它放在了Fixed Point Combinator)。

本博客文章似乎给一个很好的介绍(只脱脂的,不知道我能解释这一切......)

http://blog.jcoglan.com/2008/01/10/deriving-the-y-combinator/

var Y = function(f) { 
    return (function(g) { 
    return g(g); 
    })(function(h) { 
    return function() { 
     return f(h(h)).apply(null, arguments); 
    }; 
    }); 
}; 
var factorial = Y(function(recurse) { 
    return function(x) { 
    return x == 0 ? 1 : x * recurse(x-1); 
    }; 
}); 

factorial(5) // -> 120 

编辑: 我偷了从文章中,我不得不承认,我觉得真的很困惑,Y可能会读更好的为

var Y = function(f) { 
    var c1 = function(g) { 
     return g(g); 
    }; 
    var c2 = function(h) { 
     return function() { 
      return f(h(h)).apply(null, arguments); 
     }; 
    } 
    return c1(c2); 
}; 

而且从看它,我不知道这是一个它应该是简单的。在javascript中定义一个定点组合器的最大缺点是你需要某种懒惰的评估,以便你的函数不会无限递归。在发布简化版本之前,我必须仔细考虑和/或重新阅读文章。当然,我不确定这样的事情会对你有多大帮助,尤其是性能方面。最容易理解(也许更高性能)的解决方案可能是像其他人所建议的那样创建匿名块,通常定义该函数并从该块中返回。

0

可以传递函数的值,如果函数使用了一个名字:

setTimeout(function foo() { alert(foo); }); 
0

你不应该使用。被叫

你只是名称的功能,这只是内部范围

setTimeout(function namedFn(x) { 

    // namedFn() exists in here only (see notes below) 
    console.log('hello there ' + x); 

    if (!x || x < 10) { 
    namedFn(1 + x || 1); 
    } 

}, 5000); 

// namedFn() is undefined out here **(except for IE <= 8)**