繁体   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