简体   繁体   中英

recursive anonymous function without name

i know how to run the script by itself by using this syntax (function(){})(); , please notice my example, there is no name assigned to that anon function. the question is, how do i make recursive function with an unamed function?

(function(){
    if(i < 3){
        // how to call it self without function name?       
    }
})();

i always give anon function a name and call itself in recursive function. but this time i want to know if it's possible to call itself without a name.

I don't like Aleksandar's solution, simply because you're defining the function twice. Instead of writing an instance of the Y combinator you could write the Y combinator itself:

function y(f) {
    return function () {
        return f(y(f)).apply(this, arguments);
    };
}

Your anonymous function then becomes:

y(function (f) {
    return function (i) {
        console.log(i);
        if (i < 3) return f(i + 1);
        else return i;
    };
})(0);

The only difference is that you've now moved the recursion logic into the Y combinator. See the demo:

http://jsfiddle.net/d4w4a/

Anyway as Felix said, the only other solution is to use arguments.callee which is now deprecated. Why don't you just name your function? It's fast and it makes it easier to debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM