!function(){}()vs(function(){})() [英] !function(){ }() vs (function(){ })()

查看:124
本文介绍了!function(){}()vs(function(){})()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While reviewing some of the code written in the Twitter Bootstrap Javascript, it looks like they're calling immediately invoked anonymous functions like this:

!function( $ ) {

     ...

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

我传统上看到同样的事情就是这样:

Where I've traditionally seen this same thing accomplished this way:

(function($) {

    ...

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

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

The first way seems a bit hacky, and I'm not sure if there is any benefit or reason for doing it this way rather than the second way? Note that I understand how it works, I'm looking to understand why they chose that way to do it.

推荐答案


  • 缩小时少一个字符。

  • 应该处理其他JavaScript代码在此之前连接的位置,并且没有尾随的分号。

    • 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...

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



      im-concat-to-base.js



      im-concat-to-base.js

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

      jsFiddle

      投入领先的; 并且她工作......

      Toss in a leading ; and she works...

      jsFiddle

      ...或者喜欢Twitter Bootstrap ...

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

      jsFiddle

      这篇关于!function(){}()vs(function(){})()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆