【发布时间】:2015-09-03 22:35:30
【问题描述】:
我正在尝试使用带有链表的 setInterval 创建一个简单的任务队列。 我用linkedlist创建了一个类,一个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的工作原理:stackoverflow.com/questions/13441307/…
标签: javascript constructor setinterval member-functions