Phil
Phil

Reputation: 82

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

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 :)

function page(title) {
    this.subPages = [];
    this.title = title;
}
page.prototype.addToSubPages = function(subPage) {
    this.subPages.push(subPage);
}
page.prototype.getSubPages = function() {
    return this.subPages;
}

Now I create 2 objects:

startPage = new page("start");
somePage  = new page("foo");

...and try to add somePage into the array in startPage:

startPage.addToSubPages(somePage);

Now this doesn't seem to work, although it should be correct, if I'm not mistaken.

console.log(startPage.getSubPages());

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: startPage.getSubPages()[0].getFoo();?

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?

Upvotes: 1

Views: 97

Answers (1)

Raynos
Raynos

Reputation: 169401

function page(title) {
    this.title = title;
}

function subPage() {
    this.contentPages = [];
}
subPage.prototype = new page;

There are two problems.

  1. your not calling page in subPage.
  2. your using Child.prototype = new Parent; that's wrong, use Object.create instead

So the fixed code would be.

function page(title) {
    this.title = title;
}

function subPage(title) {
    page.call(this, title);
    this.contentPages = [];
}
subPage.prototype = Object.create(page.prototype);

Upvotes: 2

Related Questions