我正在构建一个app,它在一个对象中有一个对象数组,它自己就是一个数组。我希望能够从子对象访问父对象的属性。我知道我可以简单地通过它的索引引用父母:
var parents = [new parent()];
var parent = function() {
this.index = 0;
var children = [new child(this.index)];
}
var child = function(parentId) {
this.parent = parents[parentId];
}
但是我想知道是否有更好/更多的OO方式呢?
答案 0 :(得分:1)
您需要一些参考。对象不会自动知道其父对象。但是我认为您可以保存父对象本身,而不是保存索引。父项通过引用存储,因此如果父项被修改,则子项的父引用将反映这些更改。这在下面的代码略有改动的版本中显示:
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"