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發送消息。 任何想法?
我猜你正在尋找['bind'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/ Reference/Global_Objects/Function/bind) – hindmost
您可以在代碼中添加註釋,您認爲存在問題!我只是看了一下,'handleMessage'似乎沒有錯。我注意到的唯一錯誤是'setWebSocketConnection'! –
當我打電話給這個.IPSocket.send我得到;無法讀取未定義的'send'屬性 – moonraker