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

查看:27
本文介绍了!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);

第一种方式似乎有点老套,我不确定这样做比第二种方式有什么好处或理由?请注意,我了解它的工作原理,我想了解他们为什么选择这种方式.

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

      (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天全站免登陆