簡體   English   中英

遞歸函數調用聚合物

[英]Recursive Function Call Polymer

我正在寫一個從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參數是一個數組,並且在此情況下完全有效。

問題是在forEach回調函數內部, 是指回調函數本身的上下文。 然后,當調用this.buildMenu時,它將失敗,因為該函數未在該上下文中定義。

當使用this關鍵字時,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;
}

請注意回調后提供的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM