【问题标题】:wraping global functions in (function($){ }(jQuery)将全局函数包装在 (function($){ }(jQuery)
【发布时间】:2013-09-09 21:12:09
【问题描述】:

我正在编写一个全局 javascript 函数。在一些错误(以及这里的一些搜索)之后,我让它工作了。但我也看到了一个例子 (function($){ code here }(jQuery);

有什么区别(如果有的话),选项 1 和 2 之间有什么优势吗?两者都很好地完成了我的任务。我只是想了解其中的区别。

选项 #1

(function($){

     TEAM={
        getQB: function( success, failure) {
             var user=USER.user_data.login.toUpperCase();
             $.ajax({
             type: "GET",
             url: "/nfl/getQB?username="+user,
             dataType: 'json',
            async: false,
            success: success,
            error: failure,
             timeout: 6000
              });

           },
         getRB: function( success, failure )
            {
                 userx=USER.user_data.login.toUpperCase();
                   $.ajax({
             type: "GET",
             url: "/nfl/getRB?username="+userx,
             dataType: 'json',
            async: false,
            success: success,
            error: failure,
            timeout: 6000
                    });

            }
     }

})(jQuery);

选项 #2

    var TEAM={
        getQB: function( success, failure) {
             var user=USER.user_data.login.toUpperCase();
             $.ajax({
             type: "GET",
             url: "/nfl/getQB?username="+user,
             dataType: 'json',
            async: false,
            success: success,
            error: failure,
             timeout: 6000
              });

           },
         getRB: function( success, failure )
            {
                 userx=USER.user_data.login.toUpperCase();
                   $.ajax({
             type: "GET",
             url: "/nfl/getRB?username="+userx,
             dataType: 'json',
            async: false,
            success: success,
            error: failure,
            timeout: 6000
                    });

            }
     }

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

选项 1

(function($){ code here })(jQuery) 是一个立即调用的函数表达式。它为在其中声明的变量提供了一个临时范围。因此,在本例中,您传递的是对 JQuery 的引用,$ 将在该代码块内访问该引用。

jQuery.noConflict(); //Remove assignment to $

(function($){
  console.log($); //jQuery function 
})(jQuery)

console.log($); //undefined
console.log(jQuery); //jQuery function 

选项 2

如果您的代码不在函数范围内,它会将TEAM 附加到window 对象。这会污染全局命名空间,并且可能会导致未来出现问题。想象一下,如果有人在全局中创建了另一个具有相同名称的对象/函数。根据您的代码,您的 TEAM 可以被覆盖。

然后首选选项 1,这样您就可以避免命名空间冲突。

【讨论】:

  • 注意:要让jQuery 放弃被分配到$,您必须致电jQuery.noConflict()。否则完全正确!
  • 谢谢,亚历克斯!我忘了分配是自动的。
  • 非常感谢一百万!现在我明白为什么其他人会选择选项 1。
【解决方案2】:

在第一个选项中,您确定使用 jQuery,因为您将它作为闭包的参数传递。在第二个选项中,您可能还有其他东西在 $ 后面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多