递归 JavaScript 方法范围 [英] Recursive JavaScript Method Scope

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

问题描述

我有这个递归函数,它假设通过一个 JSON 对象来查找所有子组.这是我所拥有的:

I have this recursive function that is suppose to go through a JSON object to find all the subgroups. Here is what I have:

var subgroupIds = [];
this.getSubGroups = function (groupId) {
    this.getGroups("groupId="+groupId, function(groups) {
        if ($.isEmptyObject(groups)) {
            return subgroupIds;
        } else {
            $.each(groups, function(index,group) {
            subgroupIds.push(group.id);
                this.getSubGroups(group.id);
            });
        }
    });
}

...其中 getGroups 是一个返回所有组的异步函数.

...where getGroups is an asynchronous function that returns all the groups.

我的问题是当它进行递归调用时,我收到错误消息:

My problem is when it gets to the recursive call, I get the error that says:

Uncaught TypeError: Object #<Object> has no method 'getSubGroups' 

我猜这是一个范围问题,但我无法弄清楚它有什么问题.有什么想法吗?

I'm guessing it's a scope issue but I can't figure out what's wrong with it. Any ideas?

正如 Bergi 指出的那样,我需要回调.这就是我现在所拥有的:

As Bergi pointed out, I need to have a callback. This is what I have now:

var subgroupIds = [];
var that = this;
this.getSubGroups = function (groupId,callback) {
    this.getGroups("groupId="+groupId, function(groups) {
        if ($.isEmptyObject(groups)) {
            return;
        } else {
            $.each(groups, function(index,group) {
            subgroupIds.push(group.id);
                callback(group.id);
                that.getSubGroups(group.id);
            });
        }
    });
}

现在的问题是当我调用回调时,它说函数未定义.

The trouble now is when I call the callback, it says the function is undefined.

最终,我想返回一个子 group.id 的数组.我不知道如何到达那里...

Ultimately, I want to return an array of sub group.id's. I'm not sure how to get there...

推荐答案

这是因为 this 是在函数级别定义的,并且绑定到您正在迭代的数组中的项目在这种情况下的内部函数.内部函数中的this 与外部函数中的this 不是指同一事物.你可以通过设置来解决这个问题var that = this; 在外层并从内部函数内部引用 that

This is because this is defined at a function level, and is bound to the item in the array you're iterating over for the inner function in this case. this within the inner function does not refer to the same thing as this within the outer function. You can get around this by setting var that = this; on the outer level and referencing that from within the inner function

var subgroupIds = [];
var that = this;
this.getSubGroups = function (groupId) {
    this.getGroups("groupId="+groupId, function(groups) {
        if ($.isEmptyObject(groups)) {
            return subgroupIds;
        } else {
            $.each(groups, function(index,group) {
            subgroupIds.push(group.id);
                that.getSubGroups(group.id);
            });
        }
    });
}

有关更多信息,请参阅闭包的工作原理

这里是 这在 JS 中是如何工作的

这篇关于递归 JavaScript 方法范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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