Javascript 如何为类内的计划作业绑定此

Javascript 如何为类内的计划作业绑定此,javascript,node.js,Javascript,Node.js,我正在尝试使用节点调度在类中实现一个调度队列处理程序 但是回调具有不同类的作用域,并且不能通过this访问对象成员。有什么建议可以让它工作吗 const schedule = require('node-schedule'); class QueueHandler { constructor() { this.queue = []; this.j = schedule.scheduleJob('send', '*/10 * * * * *', this.parseNext)

我正在尝试使用
节点调度
在类中实现一个调度队列处理程序

但是回调具有不同类的作用域,并且不能通过
this
访问对象成员。有什么建议可以让它工作吗

const schedule = require('node-schedule');

class QueueHandler {
  constructor() {
    this.queue = [];
    this.j = schedule.scheduleJob('send', '*/10 * * * * *', this.parseNext);
    this.sendJob = schedule.scheduledJobs['send'];
  }

  // this one called from outside
  fillQueue(rows) {
    rows.forEach(user => {
      this.queue.push(user);
    });
  }

  parseNext() {
    if (this.queue.length > 0) {  // here comes the problem - this.queue undefined
      const next = this.queue.shift();
      // do some manipulations with the next item
    } else {
      console.log('empty queue');
    }
  }
}

module.exports.QueueHandler = QueueHandler;

答案在你的问题中,你可以使用

或者您可以使用:


谢谢,很好用。我不知道为什么,但我在发帖前第一次尝试它时,它并没有起作用。可能是打字错误。
this.j = schedule.scheduleJob('send', '*/10 * * * * *', this.parseNext.bind(this));
schedule.scheduleJob('send', '*/10 * * * * *', x=>this.parseNext(x));