我想用setInterval和链表进行简单的任务队列。 我用linkedlist创建了一个类,一个setInterval函数将继续调用一个成员函数来使用该作业。Javascript类成员函数通过setInterval调用成员函数,无法访问成员变量
function job_queue(){
this.job = null;
this.pointer = this.job;
this.job_dispatcher = null;
this.length = 0;
}
job_queue.prototype.add_job = function(job){
if(this.job == null){
console.log('1st');
this.job = {
job:job,
next:null
};
this.pointer = this.job;
this.length = 1;
}else{
console.log('2nd');
this.pointer.next = {
job:job,
next:null
};
this.pointer = this.pointer.next;
this.length++;
}
};
job_queue.prototype.event_handler = function(){
if(typeof this.job['job'] == 'undefined'){
console.log('??');
}
if(this.job.job != null){
console.log('hi');
this.job.job();
this.job = this.job.next();
}
}
job_queue.prototype.start_dispatch = function(){
if(this.job_dispatcher == null){
console.log(this.event_handler);
this.job_dispatcher = setInterval(this.event_handler,1000);
}
}
var jq = new job_queue();
function a(){
console.log('hi');
};
function b(){
console.log('hi2');
}
jq.add_job(a);
jq.add_job(b);
jq.add_job(a);
jq.start_dispatch();
然而,当event_handler函数被调用,程序崩溃与日志
if(typeof this.job['job'] == 'undefined'){
现在看来似乎无法通过调用成员函数访问成员变量的setInterval。我想问一下这些代码行到底发生了什么,我该如何实现目标?
看到这个答案对于如何'this'工作的一个解释:http://stackoverflow.com/questions/13441307/how-does-the -this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman