Different ways to execute IIFE?

2019-02-19 09:18发布

问题:

Is there any difference between

(function (){alert('')}    ())

vs

(function (){alert('')})    ()

Both works but when should I use each ?

回答1:

The wrapping parentheses are only there to force the parser to parse the construct as a function expression, rather than a function declaration. This is necessary because it's illegal to invoke a function declaration, but legal to invoke a function expression.

To that end, it doesn't matter where the invoking parentheses go. It also doesn't matter how you force the function to be parsed as an expression. The following would work just as well:

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

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

// Any unary operator will work

If you decide to use the wrapping parentheses (grouping operator), then just bear in mind that JSLint will tell you to move the invoking parentheses inside. This is simply a stylistic choice and you can ignore it if you want.



回答2:

They both do the same thing.

JSLint recommends you use the first, with the executing parentheses inside the grouping parentheses, presumably so everything's neatly grouped together.

For what it's worth, I personally think your second example is much clearer as when scanning the code you can see the execution as standing out from the function expression.

Though not a duplicate, this question covers similar ground so might be worth a look.