2015-02-08 62 views
0

我正在构建一个应用程序,该对象内有一个对象数组,其自身位于数组中。我想能够从子对象访问父对象的属性。我知道我可以简单地通过它的索引引用父像这样:OO Javascript子对象访问父项属性

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方法是什么?

+1

为什么不能简单地用'新子(这)'? – Tomalak 2015-02-08 09:34:09

+0

是你的应用程序构建一个对象树的关键,还是你只有一个一次性的对象(你称之为父对象)的情况下持有一个其他对象的数组?你想让孩子在什么意义上访问父母的财产?是否因为您想要将属性存储在所有子项共享的父项中? – 2015-02-08 09:34:56

回答

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"