2016-09-02 7 views
0

this.nameを関数イベントエミッタに渡すことができませんでした。 マイコード:Nodejs変数がイベントリスナーに渡すことができません

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

答えて

1

これはthisキーワードがバインドされている方法です。例: this articleをご覧ください。あなたのケースでは、コールバック内のthisがグローバルスコープ(ノード環境ではprocessオブジェクト、strict modeを使用しない限り、Webブラウザではwindow)にバインドされている可能性が最も高いです。

すぐに作業ができるので、変数にthisを添付して後で使用することができます。

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 
     }); 
    } 
} 
+0

を修正してくださいかっこエラー – k102

+0

@ k102完了、ありがとう –

+0

@KrzysztofZbiciński、あなたの説明をありがとう、n私の問題を解決するだけですが、教訓も教えてくれました。感謝する。 –

1

これは、thisが別のコンテキストを指しているからです。

  • var self = this;connectに機能を追加し、このようconsole.log(self.name);
  • 使用bindを呼び出す - ので、あなたは、コンテキストを変更することができます:あなたはここでは2つの選択肢があり

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

+0

ありがとうございました。 –

関連する問題