【发布时间】:2017-07-17 15:06:40
【问题描述】:
我正在尝试让递归方法在类上下文中工作。在我的课堂上,我有以下方法:
countChildren(n, levelWidth, level) {
if (n.children && n.children.length > 0) {
if (levelWidth.length <= level + 1) {
levelWidth.push(0);
}
levelWidth[level + 1] += n.children.length;
n.children.forEach(function (n) {
this.countChildren(n, levelWidth, level+1);
});
}
// Return largest openend width
return levelWidth;
}
但是,当我使用此方法时(之前我只是将其用作function countChildren = ...),它无法...找到 (?) 本身:递归时的Cannot read property 'countChildren' of undefined。
有人有什么想法吗?
【问题讨论】:
-
这是因为
forEach的回调有它自己的范围,并将this的值设置为类以外的值。
标签: javascript class recursion