2

The following node.js script is not working

var EventEmitter = require('events').EventEmitter;
var util = require('util');

var TickE = function() {    
}

util.inherits(TickE, EventEmitter); //TickE.prototype.__proto__ = EventEmitter.prototype;

TickE.prototype.ticker = function() {
    var self = this;
    setInterval (function () {
         self.emit('tick');      
    }, 1000);
};

var t = new TickE ();

//console.log (util.inspect(t));

t.on('tick', function() { console.log ('Tick...');});

t.ticker();

It is not working if I call the emit method like below

TickE.prototype.ticker = function() {
    //var self = this; // commented this line
    setInterval (function () {
         this.emit('tick'); // using this in place of self
    }, 1000);
};

self is just a variable holding reference of this and why this is throwing error ?

Kishore Relangi
  • 1,928
  • 16
  • 18

1 Answers1

6

Because the this keyword has a different value in the function that is invoked by setInterval.

You already know the solution with the self variable in a closure, a different (and shorter) solution would be binding the emit method:

setInterval(this.emit.bind(this, "tick"), 1000);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375