2010-11-27 168 views
2

我正在处理一个小型的Websockets演示,我遇到了范围问题,我无法排序。Javascript函数范围问题

network = function() { 

    this.host = "ws://localhost:8002/server.js"; 
    this.id = null; 

    this.init = function (s) { 
     var scene = s; 

     try { 
      socket = new WebSocket(this.host); 

      socket.onopen = function (msg) { 
      }; 

      socket.onmessage = function (msg) { 
       switch(msg.data[0]) { 
       case 'i': 
        var tmp = msg.data.split('_'); 

        // cant access this function. 
        this.setId(tmp[1]); 

        break; 
       } 
      }; 

      socket.onclose = function (msg) { 
      }; 
     } 
     catch (ex) {} 
    }; 

    this.setId = function(id) { 
     this.id = id; 
    }; 
}; 

如何从socket.onmessage事件访问this.setId()?

回答

2
network = function() { 
    var self = this; 

    this.host = "ws://localhost:8002/server.js"; 
    this.id = null; 

    this.init = function (s) { 
     var scene = s; 

     try { 
      socket = new WebSocket(self.host); 

      socket.onopen = function (msg) { 
      }; 

      socket.onmessage = function (msg) { 
       switch(msg.data[0]) { 
       case 'i': 
        var tmp = msg.data.split('_'); 

        // cant access this function. 
        self.setId(tmp[1]); 

        break; 
       } 
      }; 

      socket.onclose = function (msg) { 
      }; 
     } 
     catch (ex) {} 
    }; 

    this.setId = function(id) { 
     self.id = id; 
    }; 
}; 

保留这样的参考应该这样做。只要您在某个功能中参考this,请将this替换为self

+0

啊辉煌,魅力无穷。谢谢! :-) – harrynorthover 2010-11-27 18:24:18