javascript – node.js,setTimeout回调方法和“this”

我正在尝试使用node.js编写一个简单的轮询应用程序.我想编写一个EventEmitter,它对计时器执行操作,并根据该周期性操作的结果发出事件.

我首先创建自己的对象并继承自EventEmitter.我使用setInterval启动计时器,并在计时器结束后指定要调用方法.在计时器回调方法中,我想引用我创建的对象的变量,但这似乎并不引用该对象.

如何在此方法中引用我的变量?这是我的代码

var util = require('util'),events = require('events'),timers = require('timers'),redis = require('redis');


// define worker object

var JobPoller = function () {

    // inherit event emitter
    events.EventEmitter.call(this);

    // save reference to database
    this.db = redis.createClient();

    // start main loop
    this.interval_id = timers.setTimeout(this.check,1000);

};


JobPoller.prototype.check = function () {

    // pop a job off the queue if possible
    this.db.rpop('pdf-job-queue',function (err,result) {

        if (err != null)
            this.emit('error',err);

        if (result != null)
            this.emit('job',JSON.parse(result));

        // check for more jobs
        this.interval_id = timers.setTimeout(this.check,1000);

    });

};


// inhert from event emitter

util.inherits(JobPoller,events.EventEmitter);


// export the poller instance

module.exports = new JobPoller;

解决方法

this.check只是一个简单的函数,该函数内部的值将在调用函数时确定.

Node应该支持bind,所以你可以将函数绑定到你想要的函数,如下所示:

this.interval_id = timers.setTimeout(this.check.bind(this),1000);

或者,您可以使用闭包手动强制它成为您想要的:

var self = this;
this.interval_id = timers.setTimeout(function() { self.check() },1000);

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...