recursion - javascript: recursive anonymous function? -
let's have basic recursive function:
function recur(data) { data = data+1; var nothing = function() { recur(data); } nothing(); }
how if have anonymous function such as...
(function(data){ data = data+1; var nothing = function() { //something here calls function? } nothing(); })();
i'd way call function called function... i've seen scripts somewhere (i can't remember where) can tell name of function called, can't recall of information right now.
you can give function name, when you're creating function value , not "function declaration" statement. in other words:
(function foo() { foo(); })();
is stack-blowing recursive function. now, said, probably don't may not want this in general because there weird problems various implementations of javascript. (note — that's old comment; some/many/all of problems described in kangax's blog post may fixed in more modern browsers.)
when give name that, name not visible outside function (well, it's not supposed be; that's 1 of weirdnesses). it's "letrec" in lisp.
as arguments.callee
, that's disallowed in "strict" mode , considered bad thing, because makes optimizations hard. it's slower 1 might expect.
edit — if want have effect of "anonymous" function can call itself, can (assuming you're passing function callback or that):
asyncthingwithcallback(params, (function() { function recursive() { if (timetostop()) return whatever(); recursive(morework); } return recursive; })());
what define function nice, safe, not-broken-in-ie function declaration statement, creating local function name not pollute global namespace. wrapper (truly anonymous) function returns local function.
Comments
Post a Comment