简体   繁体   中英

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
    }
} 
}

This is because of how the this keyword is being bind. I strongly suggest reading eg 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
         });
    } 
}

That's because this is pointing to another context. You have two options here:

  • add var self = this; to connect function and then call console.log(self.name);
  • use bind this way - so you can change the context:

    this.client.on('connect', function(){ console.log(this.name); }.bind(this))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM