!function(){ }() vs (function(){ })()

怎甘沉沦 提交于 2019-11-26 15:24:00
  • One less character when minified.
  • The ! should handle where other JavaScript code is concatenated before this and doesn't have a trailing semi-colon.

There is not a huge difference. I would use whatever you were more comfortable with. You should probably toss something at the start of your example to avoid...

base.js

var lol = function() {
   alert(arguments[0]);
}

im-concat-to-base.js

(function() {
    // Irrelevant.
})();

jsFiddle.

Toss in a leading ; and she works...

jsFiddle.

...or a ! like the Twitter Bootstrap...

jsFiddle.

They're both ways of getting past the ambiguity in the grammar. Neither is more "hacky" than the other. It's just a style choice.

You could also do this:

0 + function( $ ) {
  // ...
} ( window.jQuery || window.ender );

Or:

parseInt(function( $ ) {
  // ...
} ( window.jQuery || window.ender ) );

Instead of the evaluation step of !undefined you could also use the void operator to remove the ambiguity:

void function($) {
     ...
}(window.jQuery || window.ender);

Has a kind of C quality to it ;-)

One answer that I've yet not seen is that it avoids surrounding your entire function with parentheses. Outside of aesthetic considerations, this can be a plus for some editors which use parentheses to determine the level of indentation of a line.

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