Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

oop

I have the following object in a JS file:

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:

//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.

How can I accomplish this?

like image 377
Sheehan Alam Avatar asked Oct 06 '11 14:10

Sheehan Alam


People also ask

How do I create a global object in JavaScript?

A global object is an object that always exists in the global scope. In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node.

How can I access data from another JavaScript file?

In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting.

Which object serves as a global object in JavaScript?

What is a global object in JavaScript? The global object in JavaScript is an always defined object that provides variables and functions, and is available anywhere. In a web browser, the global object is the window object, while it is named global in Node.


1 Answers

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);
like image 70
Matt MacLean Avatar answered Oct 18 '22 19:10

Matt MacLean