开发者

What is this? (function(){ })() [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

What does this JavaScript snippet mean?

Location of parenthesis for auto-executing anonymous JavaScript functions?

(function(){

    //something here...

})() <--//This part right here.

What exactly is 开发者_如何学Gothis )()?

What if I change it to this ())?

(function(){

    //something here...

}()) <--//Like this


This declares an anonymous function and calls it immediately.

The upside of doing this is that the variables the function uses internally are not added to the current scope, and you are also not adding a function name to the current scope either.

It is important to note that the parentheses surrounding the function declaration are not arbitrary. If you remove these, you will get an error.

Finally, you can actually pass arguments to the anonymous function using the extra parentheses, as in

(function (arg) {
   //do something with arg
})(1);

See http://jsfiddle.net/eb4d4/


They are the same.

There has to be a parenthesis either around the function definition or around the function call to make it valid Javascript syntax, but it doesn't matter which you use.

To demonstrate what it does, using a named function it would be:

function something() {}

// parenthesis around the function reference:
(something)();

// parenthesis around the function call:
(something());


It's an anonymous function that gets called immediately the () calls the function and there are ( and ) wrapping the whole thing.

( // arbitrary wrapping
(function() { // begin anon function

}) // end anon function
() // call the anon function
) // end arbitrary wrapping


The first one just wraps the function in ( ) so that it can call the function immediately with the ()

(function(){
    alert('Hi');
})();

Alerts Hi, while

function(){
    alert('Hi');
}

Doesn't do anything since your function is never executed.


That's simply an anonymous function. The () parens call the function immediately, instead of waiting for it to be called elsewhere.


Its an immediately invoked anonymous function. ()) would not work because you need () around the function before you can call it with ().

Sorta equivalent to:

function a(){}
a();


This is declaring an anonymous function and then immediately executing it. This is common for creating scoped variables.


In JavaScript, function definition is a literal - which means, it's an expression with the value of the Function object.

If you put () right after it, you effectively call the function right after defining it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜