How can I call an anonymous function recursively (from within itself)?
(function(n) {
console.log(n=n-1);
// Want to call it recursively here without naming any function
})(20);
How can I call an anonymous function recursively (from within itself)?
(function(n) {
console.log(n=n-1);
// Want to call it recursively here without naming any function
})(20);
Just name it. In this context the function won't be available outside of parentheses anyway - so you won't be polluting the namespace with it.
(function recursive(n) {
console.log(n = n - 1);
if (n > 0) {
recursive(n); // just an example
}
})(20);
//recursive(20); // won't be able to call it here...
From the pure theoretical standpoint, if you really want to avoid any names, you can use the "Y combinator", which is basically a way to call a function with itself as an argument:
(function (le) {
return (function (f) {
return f(f);
}(function (f) {
return le(function (x) {
return f(f)(x);
});
}));
})(function (f) {
return function (n) {
document.write(n + " ");
if (n > 0) f(n - 1);
}
})(20);
Here's a good explanation on how this works.
You will not be able to call it without name of without using arguments.callee
. However you can name a function this way:
(function repeat(n) {
console.log(n);
n = n - 1;
if (n > 0) repeat(n);
})(20);