Reputation: 21444
when I code:
var a =
function()
{
alert("44")
return function(){alert(33)}
}()();
is this expression evaluated in the following order?
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
Upvotes: 3
Views: 1290
Reputation: 1
i just learning self-invoking functions,too.
and i think the code should be
3. (function() { alert("44"); return function(){alert(33);} })()()
Upvotes: 0
Reputation: 26277
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.
Upvotes: 2
Reputation: 134701
function() { alert("44") return function(){alert(33)} }
you define the functionfunction() { alert("44") return function(){alert(33)} }
()
you call that function returning anonymous function function(){alert(33)}
function() { alert("44") return function(){alert(33)} }()
()
you call returned function, so it's actually equivalent to function(){alert(33)}()
So the whole execution is equivalent to:
alert("44"); alert(33);
Upvotes: 2