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

2020-03-02 02:55发布

问题:

This question already has answers here:
Closed 8 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 this )()?
What if I change it to this ())?

(function(){

    //something here...

}()) <--//Like this

回答1:

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/



回答2:

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());


回答3:

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


回答4:

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.



回答5:

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



回答6:

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();


回答7:

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



回答8:

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.