Access object in array which is a property of another object - Javascript

itsybitsyleah

New Member
It's been a long time since I learned OOP and I'm new to JS, so things might look weird for more advanced users - sorry :)\[code\]function page(title) { this.subPages = []; this.title = title;}page.prototype.addToSubPages = function(subPage) { this.subPages.push(subPage);}page.prototype.getSubPages = function() { return this.subPages;}\[/code\]Now I create 2 objects:\[code\]startPage = new page("start");somePage = new page("foo");\[/code\]...and try to add \[code\]somePage\[/code\] into the array in \[code\]startPage\[/code\]:\[code\]startPage.addToSubPages(somePage);\[/code\]Now this doesn't seem to work, although it should be correct, if I'm not mistaken.\[code\]console.log(startPage.getSubPages());\[/code\]This shows me that something is in the array, but the object appears to be empty. What am I doing wrong?Also: How would I access a certain element in that array? Like this: \[code\]startPage.getSubPages()[0].getFoo();\[/code\]?Edit: Holy Mackerel, Batman! This is more like my actual code: http://jsfiddle.net/pZHKS/2/You're all right, the code I posted actually works. As soon as inheritance comes into play, it doesn't work anymore. Why, though? It should work exactly like the code above, right?
 
Top