2016-10-04 8 views
-1

グローバルサービスを作成しようとしていて、グローバル変数をページのすべてのスクリプトに公開したいとします。 例:MyService変数はすべてのスクリプトで使用可能にする必要があります。これは、ページ上のすべてのスクリプトで使用できるjQueryと同じです。javascript:変数をクロージャからグローバリゼーションする方法

jQuery 3.1.1のソースコードを見ていました。

(function(global, factory) { 

"use strict"; 

if (typeof module === "object" && typeof module.exports === "object") { 

    // For CommonJS and CommonJS-like environments where a proper `window` 
    // is present, execute the factory and get jQuery. 
    // For environments that do not have a `window` with a `document` 
    // (such as Node.js), expose a factory as module.exports. 
    // This accentuates the need for the creation of a real `window`. 
    // e.g. var jQuery = require("jquery")(window); 
    // See ticket #14549 for more info. 
    module.exports = global.document ? 
     factory(global, true) : 
     function(w) { 
      if (!w.document) { 
       throw new Error("jQuery requires a window with a document"); 
      } 
      return factory(w); 
     }; 
} else { 
    factory(global); 
} 

// Pass this if window is not defined yet 
})(typeof window !== "undefined" ? window : this, function(window, noGlobal) { 

上記は最初から小さい部分です。これは私が似た何かをしようとしたクロージャの内部にある私の理解あたりとしてjQueryのvar

var 
version = "3.1.1", 

// Define a local copy of jQuery 
jQuery = function(selector, context) { 

    // The jQuery object is actually just the init constructor 'enhanced' 
    // Need init if jQuery is called (just allow error to be thrown if not included) 
    return new jQuery.fn.init(selector, context); 
}, 

宣言されているところ

そして、これはあります。私は私のhtmlページで上記のスクリプトが含まれており、それがクロージャ内で定義されたように私が正しいエラーをスローするJavaScriptインタプリタたMyServiceにアクセスしようとした場合

(function (jQuery) { 
    var MyService = function() { 
     console.log('hello world from service'); 
    } 
})(jQuery); 

これを解決するには、私がしたくない閉鎖の外にvar MyServiceを宣言する必要があります。

私の質問はどのようにして所望の結果を達成することができます

  1. です。
  2. なぜjQueryの場合は失敗しないのですか?
+3

1には何も変更する必要はありません別の方法:単語あなたはどこjQueryのソースコードに一部を欠場 – mplungjan

+0

'var'または2の使用' window.MyService = 'を削除彼らはそれをグローバルに公開します: 'window.jQuery = window。$ = jQuery;' –

+0

@Riteshあなたが何を意味するのか分かりません。私の以前のコメントは、「jQueryの場合にはなぜ失敗しないのですか?」 –

答えて

4
(function (jQuery, w) { 
w.MyService = function() { 
    console.log('hello world from service'); 
} 
})(jQuery, window); 

これを試してみてください;)

+0

このように、MyServiceはウィンドウオブジェクトのプロパティとして定義されています。どこからでも 'window.MyService'を使用する必要がありますが、' window.jQuery'を使用してjQueryを使用していません。 – Ritesh

+1

'MyService'または' window.MyService' ... JQueryと同じです。 'window.JQuery'それが動作します;) –

+0

これが見つかりました。完全に正常に動作します。 – Ritesh

0

あなたがそうのようなウィンドウオブジェクトの属性を設定することでこれを行うことができます。

window['hello'] = 'world';

0

これはクロージャではありません。これは自己呼び出し関数です。

var globalVar = {}; 
(function (jQuery, g) { 
g.MyService = function() { 
    console.log('hello world from service'); 
} 
})(jQuery, globalVar); 

window

// Output 

globalVar.MyService() 
hello world from service 
関連する問題