29

在查看一些用 Twitter Bootstrap Javascript 编写的代码时,看起来他们正在调用立即调用的匿名函数,如下所示:

!function( $ ) {

     ...

}(window.jQuery || window.ender);

我传统上看到同样的事情是通过这种方式完成的:

(function($) {

    ...

})(window.jQuery || window.ender);

第一种方式似乎有点hacky,我不确定这样做而不是第二种方式是否有任何好处或理由? 请注意,我了解它是如何工作的,我希望了解他们为什么选择这种方式来做到这一点。

4

4 回答 4

20
  • 缩小时少一个字符。
  • 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.

于 2011-11-29T04:41:30.680 回答
14

它们都是克服语法歧义的两种方法。两者都不比另一个更“hacky”。这只是一种风格选择。

你也可以这样做:

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

或者:

parseInt(function( $ ) {
  // ...
} ( window.jQuery || window.ender ) );
于 2011-11-29T04:41:01.540 回答
3

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 ;-)

于 2013-04-25T01:55:34.823 回答
1

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.

于 2016-09-05T14:10:23.510 回答