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

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -