グローバルサービスを作成しようとしていて、グローバル変数をページのすべてのスクリプトに公開したいとします。 例: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
を宣言する必要があります。
私の質問はどのようにして所望の結果を達成することができます
- です。
- なぜjQueryの場合は失敗しないのですか?
1には何も変更する必要はありません別の方法:単語あなたはどこjQueryのソースコードに一部を欠場 – mplungjan
'var'または2の使用' window.MyService = 'を削除彼らはそれをグローバルに公開します: 'window.jQuery = window。$ = jQuery;' –
@Riteshあなたが何を意味するのか分かりません。私の以前のコメントは、「jQueryの場合にはなぜ失敗しないのですか?」 –