I am trying to get a recursion method to work in a class context. Within my class I have the following method:
countChildren(n, levelWidth, level) {
The problem arises because within your loop, this gets redefined to the inner function scope.
countChildren(n, levelWidth, level) {
var self = this; // Get a reference to your object.
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) {
// Use "self" instead of "this" to avoid the change in scope.
self.countChildren(n, levelWidth, level+1);
});
}
// Return largest openend width
return levelWidth;
}