Question
when I code:
var a =
function()
{
alert("44")
return function(){alert(33)}
}()();
is this expression evaluated in the following order?
- define the function;
- pass its reference pointer to a
- a() is invoked
- return in a a new function pointer
- a() is invoked again
and if so why do I have a syntax error if I do:
function()
{
alert("44")
return function(){alert(33)}
}();
the interpreter wants a left operand first...
but this syntax works:
(
function()
{
alert("44")
return function(){alert(33)}
};
)()
the outer parenthesis what does meaning???
Thanks
Solution
It's the syntax of the language. If you want to in-place execute an anonymous function, you must enclose it in parens.
JS has these edge cases where the syntax is weirder than you expect. Take for example, evaling a string that has a JSON doesn't work unless it's wrapped with parens.
// Wrong
eval("{ ... }");
// Right
eval("({ ... })");
It's the syntax of the language.
That said, I think (and this is strictly IMHO), the steps you've outlined are not accurate.
- Function is defined and invoked. alert("44"); happens as a result.
- The function returns another function which is also invoked. alert("33"); happens.
- The innermost function doesn't return anything, so a is effectively undefined. typeof a returns "undefined".
OTHER TIPS
function() { alert("44") return function(){alert(33)} }
you define the functionfunction() { alert("44") return function(){alert(33)} }
()
you call that function returning anonymous functionfunction(){alert(33)}
function() { alert("44") return function(){alert(33)} }()
()
you call returned function, so it's actually equivalent tofunction(){alert(33)}()
So the whole execution is equivalent to:
alert("44"); alert(33);
i just learning self-invoking functions,too.
and i think the code should be
3. (function() { alert("44"); return function(){alert(33);} })()()