一个类中的Javascript递归 [英] Javascript recursion within a class

查看:73
本文介绍了一个类中的Javascript递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让一个递归方法在类上下文中工作。在我的班级中,我有以下方法:

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

然而,当我使用这种方法时(之前我刚刚使用它时有效) as function countChildren = ... )它不能...找到(?)本身:无法读取未定义的属性'countChildren'在递归时。

However, when I use this method (which worked before when I just used it as function countChildren = ...) it can't... find (?) itself: Cannot read property 'countChildren' of undefined at the recursion.

有没有人有任何想法?

Does anyone have any ideas?

推荐答案

问题出现了,因为在你的循环中,这个被重新定义为内部函数范围。

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;
}

这篇关于一个类中的Javascript递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆