Javascript 这个关键字在原型函数中的递归执行一次,然后未定义
Javascript this keyword in recursion in prototype functions executes once and then undefined
我创建了一个原型,里面有这个函数:
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
设置为给定值。
相关文章:
- 如果30秒未单击,请应用CSS一次,将其删除,然后重新迭代
- 一台特定计算机的Ajax请求数据未定义/失败
- Meteor和S3:如何通过一次上传/编辑定义三个不同的图像
- PassportJS/忘记密码:req.user只定义一次
- 函数在第一次触发后变为未定义
- 此变量是一个数组.为什么它返回未定义
- 为什么此代码返回未定义的4次而不是数组值
- Chrome只打开一次自定义URI
- 变量在循环的最后一次迭代中变为未定义
- Javascript 这个关键字在原型函数中的递归执行一次,然后未定义
- Javascript一直说未定义
- React和Axios触发两次(一次未定义,一次成功)
- if语句中的函数仅在第一次未定义,但在休息时间函数调用也是如此
- Jquery/Javascript在CSS改变后只运行一次自定义函数
- 使用jquery只保存一次自定义数据到dom元素
- 插入排序最后一项未定义
- 而Number原型扩展中的循环调用函数一次,然后出现未定义的错误
- React Render调用两次,第二次未定义道具
- 函数只被处理一次,然后浏览器给出错误“函数未定义”
- 第一次变量存储它是未定义的,每隔一次它的工作?使用jQuery, JavaScript, Ajax