开发者

Anonymous JavaScript function for global abatement

I've run across some strangeness in JavaScript syntax that I don't understand.

I was trying to use a single anonymous global function for global abatement, like this:

<script type="text/javascript">
  function() {
    alert("all code goes here");
  }()开发者_Go百科;
</script>

Unfortunately, I get a syntax error. This fixes it:

<script type="text/javascript">
  var MAIN = function() {
    alert("all code goes here");
  }();
</script>

But is unsatisfying because there is now a global MAIN object. Then I ran across this:

<script type="text/javascript">
  (function() {
    alert("all code goes here");
  })();
</script>

A colleague of mine saw this, shook his head and said "that's some syntax man".

What is going on with

var x = function() { .. }();

that requires parenthesis without the variable like this

(function() { ... })();

Edit: Identical to another question, with this great answer.


The issue is that function() {}() is being parsed as a function declaration. In a function declaration the function name is mandatory, so since it's missing here you get a syntax error. Placing parentheses around the function() {}() fixes the problem by forcing the code inside to be parsed as an expression instead: the parentheses act as the grouping operator, within which only an expression is valid.

Placing function() {}() on the right hand side of an assignment works for a similar reason: only an expression is valid there, so the function is parsed as an expression.

This is a short explanation. If you want a longer version, I'd suggest reading CMS's excellent explanation in another question.


Basically... Javascript requires you to put your function somewhere.

You can do this with the normal named syntax:

function foo(){}

Or with the variable assignment syntax:

var foo = function(){}

The syntax with the () is actually just the second syntax, but you throw away the result instead of storing it somewhere.

This is actually equivalent to the statement above:

var foo = (function(){})

But since you can't have an assignment without assigning it to something it won't work without the ().


So the reason is basically to disambiguate between a function declaration and a function expression.

If the extra braces or variable introduction don't sit well with you, there's always an operator you can persuade to do the work for you:

void function() {
    alert('hi');
}();


<script>
var foo = function(){alert("call");}();
var foo2 = function(){alert("call");};
console.log(foo2);
console.log(foo);

//foo(); //<-bad, foo not a function
console.log(function(){return "json";}());
</script>

var foo is undefined cause there is no return value; if we do this:

var foo = function(){return function(){alert("call");};}();
foo(); //works cause a function is assigned to foo
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜