Basically you're looking for something called the Y-Combinator (or as Wikipedia puts it the Fixed Point Combinator).
This blog post seems to give a good introduction (only skimmed it, not sure that I can explain it all...)
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
Edit:
I stole that from the article, and I have to admit, I find that really confusing, Y might read better as
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);
};
And from looking at it, I'm not sure it's as simple as it should be. The biggest drawback to defining a fixpoint combinator in javascript is you need some sort of lazy evaluation so that your function will not infinitely recurse. I'll have to think about it and/or reread the article before I can post a simplified version. Of course, I'm not sure how much something like this would help you, especially performance wise. The easiest to understand (and perhaps more performant) solution is probably to create the anonymous block like others have suggested, define the function normally and return it from the block.