最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论