Javascript 这个关键字在原型函数中的递归执行一次,然后未定义

Javascript this keyword in recursion in prototype functions executes once and then undefined

本文关键字:一次 未定义 然后 执行 递归 关键字 原型 函数 Javascript      更新时间:2023-09-26

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

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设置为给定值。