How can I access the JS object that I defined?

I have the following object:

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

How can I access the object?

 var breadcrumb = new IOBreadcrumb(); breadcrumb.add('some title','some url'); console.log(breadcrumb.breadcrumbs); 

Gives me the error Uncaught Type Error: object is not a function .

+4
source share
4 answers

The problem is that you are trying to use new for an object, but it can actually target functions. Try instead

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

Alternatively, you can also use the prototype here and share the definition of add among several instancces

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

Should do it, literally, this is not a function;)

0
source

Use IOBreadcrumb.add('some title','some url');

IOBreadcrumb is currently an object with a static add function. If you want to make an instance of IOBreadcrumb , you will make it a function.

 var IOBreadcrumb = function() { this.breadcrumbs = []; this.add = function(title, url) { this.breadcrumbs.push({ title: title, url: url }); }; }; var breadcrumb = new IOBreadcrumb(); breadcrumb.add('some title','some url'); 
0
source
 function createIOBreadcrumb() { return { breadcrumbs: [], add: function(title, url) { var crumb = { title: title, url:url }; this.breadcrumbs.push(crumb); }; }; } var breadcrumb = createIOBreadcrumb(); 
0
source

All Articles