[英]Javascript this keyword in recursion in prototype functions executes once and then undefined
I have created a prototype and I have this function in it: 我已经创建了一个原型,并且在其中具有以下功能:
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();
});
},
Which is being called by the function commit
由函数
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();
},
The point of this is, I have an array named queue
, it can store any functions in it. 关键是,我有一个名为
queue
的数组,它可以在其中存储任何函数。 So I want to add many functions into the queue
array and then when I call commit()
I want it to execute all of these functions. 因此,我想将许多函数添加到
queue
数组中,然后在我调用commit()
希望它执行所有这些函数。 However, I don't want it to execute all of them at once, but I want them to execute in a queue (wait till each one is done, then execute the next one). 但是,我不希望它一次执行所有操作,而是希望它们在队列中执行(等待每个操作完成,然后执行下一个操作)。
I have used recursion to create this, but I am falling in the following problem: 我已经使用递归来创建它,但是我遇到了以下问题:
when workRequests
function gets called for the first time, everything works fine, but after inside the function it calls workRequests()
, I will get the following error: 首次调用
workRequests
函数时,一切正常,但是在函数内部调用workRequests()
,我将得到以下错误:
Uncaught TypeError: Cannot read property 'queue' of undefined
I am no expert with javascript so I don't really understand what happens behind the scenes that makes the this
keyword lose it's value that used to be the same in the first call of workRequests()
. 我不是javascript专家,所以我真的不太了解幕后发生的事情,这使
this
关键字失去了与第一次调用workRequests()
相同的值。
I call the whole thing like this: 我这样称呼整个事情:
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();
An help solving the error would be very appreciated, thanks! 非常感谢您对解决错误的帮助,谢谢!
You have to explicitly arrange for this
to be set: 您必须明确安排
this
设置:
var request = this.queue.shift();
var self = this;
request(function() {
workRequests.call(self);
});
Slightly simpler maybe: 可能稍微简单一些:
var request = this.queue.shift();
request(workRequests.bind(this));
The .bind()
method returns a function that calls your function such that this
will be set to the given value. 该
.bind()
方法返回调用你的函数,使得函数this
将被设置为给定值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.