在(function($){}(jQuery)中包装全局函数

时间:2013-09-09 21:12:10

标签: javascript jquery ajax

我正在编写一个全局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
                    });

            }
     }

2 个答案:

答案 0 :(得分:2)

选项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,以避免命名空间冲突。

答案 1 :(得分:0)

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