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

2020-03-02 03:13发布

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

8条回答
看我几分像从前
2楼-- · 2020-03-02 03:16

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

查看更多
地球回转人心会变
3楼-- · 2020-03-02 03:16

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

查看更多
劫难
4楼-- · 2020-03-02 03:22

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
查看更多
家丑人穷心不美
5楼-- · 2020-03-02 03:23

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/

查看更多
仙女界的扛把子
6楼-- · 2020-03-02 03:26

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.

查看更多
我命由我不由天
7楼-- · 2020-03-02 03:27

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();
查看更多
登录 后发表回答