我想獲得遞歸方法在類上下文中工作。在我的課,我有以下方法:一個類內的Javascript遞歸
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