2016-02-12 89 views
1

我在寫一個遞歸地從JSON對象構建菜單樹的元素。然而,當函數調用本身我得到的錯誤:this.buildMenu is not a function遞歸函數調用聚合物

這裏的buildMenu

buildMenu: function(items) { 
var node = new Array(); 

items.forEach(function(elem,index,arr) { 
    node.push(elem.Name); 

    if (elem.SubBranch.length > 0) { 
     return this.buildMenu(elem.SubBranch); //error is here 
    } 
}); 

return node; 
} 

調用buildMenu最初的方法

handleRes: function() { 
    this.response = this.$.categoryList.lastResponse; 
    this.menuItems = this.buildMenu(this.response); 
    //... 
} 

我驗證過的數據是存在的,正確格式化。如果我註釋掉遞歸調用,我會得到第一層結果。所以,它在這方面工作。

在遞歸調用中調用的參數elem.SubBranch是一個數組,並且完全有效,如果這很重要的話。

+0

你可以建立一個蹲點來證明問題嗎? –

回答

7

問題是,在forEach回調函數中,這個引用了回調函數本身的上下文。然後,調用this.buildMenu時,它會失敗,因爲該函數沒有在該上下文中定義。

當使用關鍵字時,forEach函數接受參數以提供要使用的對象。在這種情況下,你可以使用下面的代碼:

buildMenu: function(items) { 
var node = new Array(); 

items.forEach(function(elem,index,arr) { 
    node.push(elem.Name); 

    if (elem.SubBranch.length > 0) { 
     return this.buildMenu(elem.SubBranch); //error is here 
    } 
}, this); 

return node; 
} 

注意回調後提供的參數。