0

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.

Dariel Pratama
  • 1,607
  • 3
  • 18
  • 49

1 Answers1

0

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.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299