Javascript this 关键字在原型(prototype)函数中的递归中执行一次然后未定义

标签 javascript jquery recursion

我创建了一个原型(prototype),里面有这个函数:

workRequests:
/**
 * Works out all requests in the queue with
 */
function workRequests() {

    /**
     * Checks if queue of requests is empty
     */
    if (this.queue.length == 0) {
        this.setDone(true);
        return;
    }

    /**
     * Gets the next request
     */
    var request = this.queue.shift();
    request(function() {
        workRequests();
    });

},

由函数 commit 调用

commit:
/**
 * Executes all requests till there are no requests left
 */
function commit() {
    console.log("committed");
    /**
     * Make sure the system is already committing all
     */
    running = true;
    this.workRequests();
},

重点是,我有一个名为 queue 的数组,它可以在其中存储任何函数。因此,我想将许多函数添加到 queue 数组中,然后当我调用 commit() 时,我希望它执行所有这些函数。但是,我不希望它立即执行所有这些,而是​​希望它们在队列中执行(等到每个完成后,然后执行下一个)。

我使用递归来创建这个,但我遇到了以下问题:

当第一次调用 workRequests 函数时,一切正常,但是在函数内部调用 workRequests() 后,我会收到以下错误:

Uncaught TypeError: Cannot read property 'queue' of undefined

我不是 JavaScript 专家,所以我不太明白幕后发生了什么,导致 this 关键字失去了它在第一次调用 时相同的值workRequests().

我这样称呼整个事情:

var reqs = new SyncRequests();
for(var i = 0; i < 5; i++) {
    reqs.executeRequest(function(callback) {
        $.ajax({
            type: "POST",
            async: true,
            url: 'www.google.com',
            data:  {direction: 'up' },
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (msg) {
                callback();
            },
            error: function (err) {
                callback();
            }
        });
    });
}
reqs.commit();

如果能帮助解决该错误,我们将不胜感激,谢谢!

最佳答案

您必须明确安排要设置的this:

var request = this.queue.shift();
var self = this;
request(function() {
    workRequests.call(self);
});

也许稍微简单一点:

var request = this.queue.shift();
request(workRequests.bind(this));

.bind() 方法返回一个调用您的函数的函数,以便将 this 设置为给定值。

关于Javascript this 关键字在原型(prototype)函数中的递归中执行一次然后未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27808346/

相关文章:

javascript - 是否有可能用柏树验证阻塞字段?

javascript - 如何使用 JavaScript 或 jQuery 在客户端将 html 页面导出为 pdf?

javascript - 在导航栏中突出显示当前部分

jquery最接近的tr没有被选中

c - 带指针的递归 -C

javascript - 更换DIV?

javascript - Array.map 使用箭头函数在 redux reducer 中返回 null

jquery - 在 jQuery AJAX 帖子中,是否有可能不发送数据有效负载?

javascript - 了解递归函数在 javascript 中的工作原理

java - 回溯的一些麻烦