Reputation: 15
I am building an app which has an array of objects within an object which it's self is in an array. I want to be able to access the parent object's properties from the child object. I know I can simply reference the parent by it's index like so :
var parents = [new parent()];
var parent = function() {
this.index = 0;
var children = [new child(this.index)];
}
var child = function(parentId) {
this.parent = parents[parentId];
}
But I want to know if there is a better/ more OO way of doing it?
Upvotes: 0
Views: 413
Reputation: 116110
You will need some reference. An object does not know its parent automatically. But instead of saving an index, I think you can save the parent object itself. The parent is stored by reference, so if the parent is modified, the parent reference of the child reflects those changes. This is shown below in a slightly altered version of your code:
function parent() {
this.index = 0;
// Make children a property (for this test case) and
// pass 'this' (the parent itself) to a child's constructor.
this.children = [new child(this)];
}
function child(parent) {
// Store the parent reference.
this.parent = parent;
}
// Do this after the functions are declared. ;)
var parents = [new parent()];
// Set a property of the parent.
parents[0].test = "Hello";
// Read back the property through the parent property of a child.
alert(parents[0].children[0].parent.test); // Shows "Hello"
Upvotes: 1