0

私はグローバルなJavaScript関数を書いていました。そして、いくつかの間違い(およびここでいくつかの検索)の後、私はそれを機能させました。code here しかし、 (function($){ }(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
                    });

            }
     }
4

2 に答える 2

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 が優先されます。

于 2013-09-09T21:19:01.453 に答える
0

最初のオプションでは、jQuery をクロージャーのパラメーターとして渡しているため、確実に jQuery を使用しています。2 番目のオプションでは、 $の後ろに何か他のものがあるかもしれません。

于 2013-09-09T21:16:13.143 に答える