I am trying to create an object with an array of objects. Eg: I would like to create a Page object with multiple headers. I need an addHeader() and getHeaders() method. A header itself is an object with few properties (eg name and id). I've been trying to nest it inside the page object as its part and add it to an array of Headers (which I assumed would be a part of Page, but that may not be the ideal solution). I run into trouble when I tried to execute the inner functions. I read this question and few similar on the topic, unfortunately I can't come up with a solution:
No ways to have class-based objects in javascript?
My most up to date attempt:
var Page = ( function () {
function Page() {
var headers = [];
var header = {
name:'',
id:'',
addHeader : function(name,id) {
this.name = name;
this.id = id;
Page.headers.push(header);
}
};
this.getHeaders = function() {
for(var i=0; i< Page.headers.length; i++) {
console.log(Page.headers[i]);
}
}
}
return Page;
}) ();
When I'm trying to run getHeaders:
var p = new Page(); p.getHeaders();
I get:
p.getHeaders is not a function
My javascript skills are rather basic, I would appreciate any help or comments. Thank you for your answers.
Could someone explain to me how can I access the inner addHeader function? Is this the correct way of nesting functions in javascript objects?