Different ways to execute IIFE?

我怕爱的太早我们不能终老 提交于 2019-12-30 11:12:21

问题


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.



来源:https://stackoverflow.com/questions/15428964/different-ways-to-execute-iife

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!