javascript - Nodejs variable can't pass to event listener -


this.name couldn't pass function event emitter, idea? code:

function lightwaretx(name,ip){ this.name = name; this. ip = ip;  this.connect = function(){     this.client = net.createconnection(10001,this.ip);     this.reconnectsts = true;      this.client.on('connect', function(){         console.log(this.name);         //undefined     } }  } 

this because of how this keyword being bind. suggest reading e.g. this article learn how fundamental process works. in case, this within callback bound global scope (which process object in node environment , window in web browsers, unless use strict mode).

as quick workaroud, can attach this variable, , use later.

function lightwaretx(name,ip){     var self = this;     this.name = name;     this. ip = ip;      this.connect = function(){          this.client = net.createconnection(10001,this.ip);          this.reconnectsts = true;           this.client.on('connect', function(){              console.log(self.name);              //name          });     }  } 

Comments