2016-10-04 67 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); 
}, 

按我的理解,这是一个封闭我试图做类似的东西在里面。

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

如果我包括我的html页面上面的脚本并尝试访问的MyService JavaScript解释器会抛出错误我是正确的,因为这是一个封闭的内部规定。

为了解决这个问题,我必须在闭包之外声明var MyService,我不想这样做。

我的问题是

  1. 我怎样才能达到预期的效果。
  2. 为什么它没有失败的情况下jQuery。
+3

1改变什么:删除单词'var'或2使用'window.MyService =' – mplungjan

+0

你错过jQuery的源代码,其中部分他们全局公开:'window.jQuery = window。$ = jQuery;' –

+0

@Ritesh我不确定你的意思。我以前的评论是关于:为什么它没有失败的情况下jQuery'?! –

回答

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

试试这个;)

+0

这种方式MyService被定义为windows对象的属性,并且比任何地方都要使用'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