Leong Sze Kim Leong Sze Kim - 3 months ago 13
Node.js Question

Nodejs variable can't pass to event listener

this.name couldn't pass to my function event emitter, Any idea?
My 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
}
}
}

Answer

This is because of how the this keyword is being bind. I strongly suggest reading e.g. this article to learn how this fundamental process works. In your case, this within the callback was most probably bound to a global scope (which is process object in node environment and window in web browsers, unless you use strict mode).

As a quick workaroud, you can attach this to a variable, and use it 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
         });
    } 
}