2015-02-08 64 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"