javascript - Why does the function expression in an IIFE have to be wrapped in parentheses? - Stack Overflow

I have the code : function (i){alert(i);}(3);I don't understand why I don't see the alert.

I have the code :

function (i)
{
    alert(i);
}(3);

I don't understand why I don't see the alert.

What does this syntax mean?

And why this code:

( function (i)
{
    alert(i);
}(3))();         

Does work?

What is the difference?

What Am I Missing?

I have the code :

function (i)
{
    alert(i);
}(3);

I don't understand why I don't see the alert.

What does this syntax mean?

And why this code:

( function (i)
{
    alert(i);
}(3))();         

Does work?

What is the difference?

What Am I Missing?

Share Improve this question edited Dec 26, 2024 at 9:47 dumbass 27.3k4 gold badges38 silver badges74 bronze badges asked Nov 2, 2011 at 9:38 Royi NamirRoyi Namir 149k144 gold badges493 silver badges831 bronze badges 1
  • On FireFox: "SyntaxError: function statement requires a name." – Thilo Commented Nov 2, 2011 at 9:43
Add a ment  | 

2 Answers 2

Reset to default 9

The first snippet will be interpreted as function declaration, which needs a name and your function does not have one. So this will result in an error.

Surrounding the function definition with parenthesis makes the function to be interpreted as function expression which doesn't need a name, so it is valid JavaScript.

Though it seems you are making two invocations there. It should either be

(function(i){ alert(i); }(3));

or

(function(i){ alert(i); })(3); 

Typically you can have function expression either in parenthesis (everything is evaluated as expression there) or at the right side of an assignment expression (var a = function...).

See Section 13 of the ECMAScript 5 specification:

FunctionDeclaration :
function Identifier ( FormalParameterListopt ) {FunctionBody}

FunctionExpression :
function Identifieropt (FormalParameterListopt ) {FunctionBody}

The ()-operator is responsible for executing a function, therefore a function expression which is wrapped by () is exectued immediately.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745109104a4611739.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信