简体   繁体   English

OO Javascript子对象访问父属性

[英]OO Javascript child object access to parent properties

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? 但是我想知道是否有更好/更多的OO方法呢?

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" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM