Why use (function(){})() or !function(){}()?

2019-04-11 12:19发布

问题:

I was reading In JavaScript, what is the advantage of !function(){}() over (function () {})()? then it hit me, why use :

(function(){})() or !function(){}() instead of just function(){}()?

Is there any specific reason?

回答1:

It depends on where you write this. function(){}() by itself will generate a syntax error as it is evaluated as function declaration and those need names.

By using parenthesis or the not operator, you enforce it to be interpreted as function expression, which don't need names.

In case where it would be treated as expression anyway, you can omit the parenthesis or the operator.



回答2:

I guess you are asking why use:

var fn = (function(){}());

versus:

var fn = function(){}();

The simple answer for me is that often the function on the RHS is long and it's not until I get to the bottom and see the closing () that I realise I've been reading a function expression and not a function assignment.

A full explanation is in Peter Michaux's An Important Pair of Parens.



回答3:

A slight variation on RobG's answer.

Many scripts encompass the entire program in one function to ensure proper scoping. This function is then immediately run using the double parentheses at the end. However, this is slightly different then programs which define a function that can be used in the page but not run initially.

The only difference between these two scenarios is the last two characters (the addition of the double parentheses). Since these could be very long programs, the initial parenthesis is there to indicate that "this will be run immediately."

Is it necessary for the program to run? No. Is it helpful for someone looking at the code and trying to understand it? Yes.