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:41

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楼-- · 2020-03-02 03:42

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.

查看更多
登录 后发表回答