2017-03-01 78 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();

相关问题