简体   繁体   English

如何创建可以在我的JS文件之外访问的全局javascript对象?

[英]How can I create a global javascript object that can be accessed outside of my JS file?

I have the following object in a JS file: 我在JS文件中有以下对象:

var IOBreadcrumb = function IOBreadcrumb() {
    this.breadcrumbs = [];
    this.add = function(title, url) {
      var crumb = {
        title: title, 
        url:url
      };
      this.breadcrumbs.push(crumb);
    };
  };

In another JS file I want to utilize this object: 在另一个JS文件中我想利用这个对象:

//this occurs in some on click event
var breadcrumb = new IOBreadcrumb();
breadcrumb.add('some title',url);
console.log(breadcrumb.breadcrumbs);

I would like there to only be 1 instance of IOBreadcrumb, so that when I click on a button, it will always add a breadcrumb to the array. 我希望只有1个IOBreadcrumb实例,所以当我点击一个按钮时,它总是会向数组中添加一个breadcrumb。

How can I accomplish this? 我怎么能做到这一点?

var IOBreadcrumb = {
    breadcrumbs: [],
    add: function(title, url) {
      var crumb = {
        title: title, 
        url:url
      };
      IOBreadcrumb.breadcrumbs.push(crumb);
    }
  };

Then: 然后:

IOBreadcrumb.add('some title',url);
console.log(IOBreadcrumb.breadcrumbs);

Make something like the following the first javascript that get's executed by your page. 制作类似以下内容的第一个由您的页面执行的javascript。

(function(){
    var setup = function IOBreadcrumb() {
        this.breadcrumbs = [];
        this.add = function(title, url) {
            console.log('adding');
            var crumb = {
                title: title, 
                url:url
              };
            this.breadcrumbs.push(crumb);
        }
    };


  window.IOBreadcrumb = new setup();
})(window);

That does the initial setup. 这是初始设置。 Now from anywhere you can do 现在你可以在任何地方做

IOBreadcrumb.add()

I've tested this at http://jsfiddle.net/xmHh5/ 我在http://jsfiddle.net/xmHh5/测试了这个

What this does is assign window.IOBreadcrumb to the result of a function that is executed immediately. 这样做是将window.IOBreadcrumb赋给立即执行的函数的结果。 Since there is no handle to this function, there is no way to re-execute it. 由于此函数没有句柄,因此无法重新执行它。 Since you are putting IOBreadcrumb on the window object, its effectively global. 由于您将IOBreadcrumb放在窗口对象上,因此它实际上是全局的。 I'm assuming this is running in a browser; 我假设这是在浏览器中运行; it won't run on node.js or anything because it depends on window . 它不会在node.js或任何东西上运行,因为它依赖于window

Another option is to use the Module pattern , which has the benefits of keeping breadcrumbs truly private. 另一个选择是使用Module模式 ,它具有保持面包屑真正私密的好处。 Not everyone is a fan of the module pattern though since it prevents monkey patching. 不是每个人都是模块模式的粉丝,因为它可以防止猴子修补。 This is especially problematic when you're using a library and you need to modify behavior but you don't want to edit their source files to minimize troubles when upgrading. 当您使用库并且需要修改行为但是您不想编辑其源文件以最小化升级时的麻烦时,这尤其成问题。 http://snook.ca/archives/javascript/no-love-for-module-pattern http://snook.ca/archives/javascript/no-love-for-module-pattern

var IOBreadcrumb = (function() {
    var breadcrumbs = [];
    return {
       add: function(title, url) {
          breadcrumbs.push({
             title: title,
             url: url
          });
       },

       each: function (callback) {
          for (var i=0; i < breadcrumbs.length; i++) {
               callback(breadcrumbs[i].title, breadcrumbs[i].url);
          }
      }
    }
})();

IOBreadcrumb.add('title A', 'http://url.com/A');
IOBreadcrumb.add('title B', 'http://url.com/B');
IOBreadcrumb.add('title C', 'http://url.com/C');

IOBreadcrumb.each(function(title, url){
         console.log('Title', title, 'Url', url);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建JavaScript数据类型(通过键和索引访问) - How can I create a javascript data type (accessed with key and index) 我如何在另一个JavaScript文件a.js中的b.js中创建“ Todo”模型的对象 - How can i create object of 'Todo' model in b.js which is in another javascript file a.js 如何在JavaScript中显示已访问对象的键 - How can I display the key of an accessed object in javascript 如何为我的 JavaScript 创建自己的 vsdoc.js 文件? - How can I create my own vsdoc.js file for my JavaScript? 如何创建可以从外部javascript以及asp.net网站访问的全局变量 - How to create a global variable that can be accessed from external javascript as well as asp.net website 如何在JavaScript中定义可在所有函数中访问的全局变量 - How to define a global variable in JavaScript that can be accessed in all the functions 我可以在所有JavaScript之外创建一个命名空间并像这样使用它吗: - Can I create a namespace outside of all my javascript and use it like this: 如何在一个可以被其他函数(JavaScript)访问的函数中定义全局变量? - How do I define a global variable in a function that can be accessed by other functions (JavaScript)? 我如何从angular之外的javascript函数中获取angular js创建的对象的实例 - How can i get an instance of object created by angular js from javascript function outside angular 如何将 numeric.js 导入我的 javascript 文件 - How can I import numeric.js to my javascript file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM