node.js - this.emit is not working but self.emit is working. why? -
the following node.js script 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 not working if call emit method below
ticke.prototype.ticker = function() { //var self = this; // commented line setinterval (function () { this.emit('tick'); // using in place of self }, 1000); }; self variable holding reference of , why throwing error ?
because the this keyword has different value in function invoked setinterval.
you know solution self variable in closure, different (and shorter) solution binding emit method:
setinterval(this.emit.bind(this, "tick"), 1000);
Comments
Post a Comment