Ludo
Ludo

Reputation: 5280

How to access parent object properties?

I would like to know if it's possible from an object to access the properties of its parent, here is an explicite example, let's say we have an array of People objects in a Group object.

In this Group object, every People have the same address, so it will be nice to declare it in the Group and not in each People objects, but how to access it without parsing the collection?

function Group() {
  this.address = 'EveryWhere';
  this.Collection = [];
} 

function People(data) {
  this.name = data.name;

  this.getAddress = function() {
    return this.address; //how to access it (declared in the Group object)?
  }
}

var Serie = new Group();
var John = new People();
Serie.Collection.push(John);
console.log(John.getAddress());

Upvotes: 2

Views: 1990

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

You can mimic inheritance by assigning a new Group object to the People.prototype

function Group() {
  this.address = 'EveryWhere';
  this.Collection = [];
} 


function People(data) {
  this.name = data.name;

  this.getAddress = function() {
    return this.address; //how to access it (declared in the Group object)?
  }
};

People.prototype = new Group();

var Serie = new Group();
var John = new People({name:"John"});
console.log(John.getAddress());

Upvotes: 1

Peter
Peter

Reputation: 14128

Same as in many languages: pass the parent into the constructor of the child so you can hold a reference to it.

function People(data, parent) {
    this.parent = parent;
    this.getAddress = function() {
        return this.parent.address;
    }
}

To make it safer, you can add a method on the parent to add children:

function Group() {
    // ... other code ...
    function addPeople(data) {
        this.collection.push(new People(data, this);
    }
}

Upvotes: 2

Related Questions