Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this kind of function invocation is wrong in JavaScript?

I'd like to create an anonymous function and then invoke it immediately.

1) This will bring a syntax error. Why?

function ()
{
    alert("hello");
}();

2) wrap the function definition with () and it works.

(function ()
{
    alert("hello");
})();

3) or, assign the anonymous function to a variable. It works.

var dummy = function()
{
    alert("hello");
}();

Why the first way doesn't work?

like image 217
Morgan Cheng Avatar asked Mar 22 '09 06:03

Morgan Cheng


People also ask

What is function invocation in JavaScript?

JavaScript Function Invocation is used to executes the function code and it is common to use the term “call a function” instead of “invoke a function”. The code inside a function is executed when the function is invoked.

What is illegal invocation JavaScript?

An "illegal invocation" error is thrown when calling a function whose this keyword doesn't refer to the object where it originally did. In other words, the original "context" of the function is lost.

Which function should never be used to run JS?

Never use eval()! eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.


1 Answers

The ECMAScript Language Specification, section 12.4, says:

An ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

So your case 1 is not allowed, because it might lead to ambiguities in the language. The other cases are different kinds of statements (not ExpressionStatements) in which this is not a problem, so the construct is allowed there.

like image 91
sth Avatar answered Oct 12 '22 22:10

sth