Javascript recursion within a class

后端 未结 5 1007
轻奢々
轻奢々 2020-12-31 09:28

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) {
            


        
5条回答
  •  感情败类
    2020-12-31 09:56

    Try binding the method in the constructor.
    Also, by using an arrow function for your forEach, you keep the scope of the class' this.

    export class MyClass {
        constructor(){
            this.countChildren = this.countChildren.bind(this);
        }
    
        countChildren(n, levelWidth, level){ ... }
    
    
        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( n => { // arrow function do not need to rebind this
                    this.countChildren(n, levelWidth, level+1);
                });    
            }
            // Return largest openend width
            return levelWidth;
        }
    }
    

提交回复
热议问题