递归函数调用聚合物
Recursive Function Call Polymer
我正在编写一个从 JSON 对象递归构建菜单树的元素。但是,当函数调用自身时,出现错误:this.buildMenu is not a function
这是构建菜单
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 指的是回调函数本身的上下文。然后,当调用 this.buildMenu 时,它会失败,因为该函数未在该上下文中定义。
forEach 函数接受一个参数,以提供在使用 this 关键字时要使用的对象。在这种情况下,您可以使用以下代码:
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;
}
注意回调后提供的this参数。
我正在编写一个从 JSON 对象递归构建菜单树的元素。但是,当函数调用自身时,出现错误:this.buildMenu is not a function
这是构建菜单
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 指的是回调函数本身的上下文。然后,当调用 this.buildMenu 时,它会失败,因为该函数未在该上下文中定义。
forEach 函数接受一个参数,以提供在使用 this 关键字时要使用的对象。在这种情况下,您可以使用以下代码:
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;
}
注意回调后提供的this参数。