我想写一个全局服务,并希望在页面上的所有脚本公开全局变量。 例如: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);
},
按我的理解,这是一个封闭我试图做类似的东西在里面。
(function (jQuery) {
var MyService = function() {
console.log('hello world from service');
}
})(jQuery);
如果我包括我的html页面上面的脚本并尝试访问的MyService JavaScript解释器会抛出错误我是正确的,因为这是一个封闭的内部规定。
为了解决这个问题,我必须在闭包之外声明var MyService
,我不想这样做。
我的问题是
- 我怎样才能达到预期的效果。
- 为什么它没有失败的情况下jQuery。
1改变什么:删除单词'var'或2使用'window.MyService =' – mplungjan
你错过jQuery的源代码,其中部分他们全局公开:'window.jQuery = window。$ = jQuery;' –
@Ritesh我不确定你的意思。我以前的评论是关于:为什么它没有失败的情况下jQuery'?! –