2017-03-01 61 views
0

我有以下代碼:從原型函數訪問類的成員變量中的回調在Javascript

function MyClass(udpSocket) 
{ 
    this.IPSocket = udpSocket; 
    this.port; 
    this.DestAddr; 
} 

MyClass.prototype.handleMessage = function(message) 
{ 

var msg = JSON.parse(message); 

    switch(msg.type) 
    { 
     case "Send": 
     var BufToSend = "Hey"; 
     this.IPSocket.send(BufToSend, 0, BufToSend.length, this.port, this.DestAddr, function(err, bytes) 
     { 
      if (err) throw err; 
     }); 
    break; 

MyClass.prototype.setWebSocketConnection = function(ws) 
{ 
    this.wsConnection = ws; 


    this.wsConnection.on('message', function incoming(message) 
    { 
     MyClass.prototype.handleMessage(message); 
    }); 
} 

MyClass.prototype.setUdpPort = function(PORT) 
{ 
    this.port = PORT; 
} 

MyClass.prototype.setDestAddr = function(DEST_ADDR) 
{ 
    this.DestAddr = DEST_ADDR; 
} 

exports.mMyClass = MyClass; 

問題是,當我進入回調的handleMessage我必須在MYCLASS成員變量和爲此上午進不去無法通過udpSocket發送消息。 任何想法?

+0

我猜你正在尋找['bind'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/ Reference/Global_Objects/Function/bind) – hindmost

+0

您可以在代碼中添加註釋,您認爲存在問題!我只是看了一下,'handleMessage'似乎沒有錯。我注意到的唯一錯誤是'setWebSocketConnection'! –

+0

當我打電話給這個.IPSocket.send我得到;無法讀取未定義的'send'屬性 – moonraker

回答

0

如果將指針保存爲this,則可以在回調函數內引用它。這裏有一個簡單的例子:

var MyClass = function(prop) { 
 
    this.prop = prop; 
 
}; 
 

 
MyClass.prototype.printProp = function() { 
 
    
 
    var innerFunction = function(callback) { 
 
    callback(); 
 
    }; 
 
    
 
    innerFunction(function() { 
 
    console.log('without the referece to the correct "this": ', this.prop); 
 
    }); 
 
    
 
    var that = this; 
 
    innerFunction(function() { 
 
    console.log('with the referece: ', that.prop); 
 
    }); 
 
    
 
}; 
 

 
var instance = new MyClass('hi there'); 
 

 
instance.printProp();

相關問題