2011-02-09 61 views
0

我有一個自定義對象,其中包含一個數組(稱爲「children」),其中將存儲相同類型的對象,以創建樹的結果。
比方說,它看起來像這樣:在javascript中使用樹遍歷方法擴展對象

function CustomObject(){ 
    if (this instanceof Topic) { 
    this.text = "Test"; 
    this.children = []; 
    } else 
     return new CustomObject(); } 

現在,我想一個「FORALL」的方法添加到這個對象,將在深度執行作爲參數提供的另一個功能,那樹上的所有元素 - 第一時尚。什麼是最好的方式來做到這一點?

回答

1

是這樣的嗎?

CustomObject.prototype.forAll = function(func) { 
    // process this object first 
    func(this); 

    // then process children 
    for (var i = 0; i < this.children.length; i++) 
    this.children[i].forAll(func); 
} 
+0

不幸的是,似乎沒有工作。它似乎只在第一個元素上執行,然後退出時出現錯誤。它可以在這裏嘗試:http://dl.dropbox.com/u/118505/psychojs/p.html – 2011-02-10 07:35:14