2013-08-19 96 views
0

我的客戶「下課」看起來是這樣的:超出範圍的回調函數

var Client = (function() { 
    function Client(socket) 
    { 
     this.socket = socket; 
     this.country_code = null; 

     var that = this; 

     this.socket.on('message', function(data) { 
      var r = JSON.parse(data); 

      switch (r.action) { 
       case 'init': 
        that.country_code = r.country_code; 

        break; 
      } 
     }); 
    } 

    Client.prototype.message_handler = function(data) 
    { 
    }; 

    return Client; 
})(); 

我利用websocket.io模塊從客戶端接收消息。現在,上面的代碼工作,但我真的很想有Client.prototype.message_handler,使構造函數應該是這樣的:

function Client(socket) 
{ 
    this.socket = socket; 
    this.country_code = null; 

    this.socket.on('message', this.message_handler); 
}

然而,問題是,現在在MESSAGE_HANDLER功能

Client.prototype.message_handler = function(data) 
{ 
    var r = JSON.parse(data); 

    switch (r.action) { 
     case 'init': 
      this.country_code = r.country_code; // Doesn't work. 

      break; 
    } 
};

this未解析爲客戶級別。有沒有反正通過或this通過this.socket.on('message', this.message_handler)功能?這樣,我可以在不同的處理程序中使用繼承。

回答

1

使用描述here描述的Javascript Function.prototype.bind功能。你的情況,你可以這樣做(更新感謝@ nhaa123的修復):

this.socket.on('message', this.message_handler.bind(this)); 

然後套接字的消息處理程序總是被綁定到客戶端的實例。

+1

謝謝,但不會工作。 console.log(this.country_code)裏面的message_handler仍然給未定義... E:明白了:this.socket.on('message',this.message_handler.bind(this)); – nhaa123

+0

我會更新我的答案,以便其他人看到可以在那裏工作的東西,但我對爲什麼舊版本無法正常工作感到困惑。嗯... – disatisfieddinosaur