在Javascript

时间:2017-03-01 09:09:03

标签: javascript javascript-events scope this javascript-objects

我有以下代码:

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发送消息。 任何想法?

1 个答案:

答案 0 :(得分: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();