我正在尝试在类的上下文中使用递归方法。在我的类内部,我有以下方法:
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
的值设置为类之外的其他内容。 - adeneo