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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With