0

我想知道是否有人可以帮助我。来自 Java、C++ 背景,我正在尝试用 Javascript 编写一个简洁的 OO 实现。我在 Socket.io 中使用以下模式。

在监听函数中,实例变量在第一个警报上正确定义。x 实例变量超出了 socket.on 事件侦听器的范围,并且两个实例变量都超出了 JQuery $.each 的范围

有人可以解释这里发生了什么吗?

var Player = (function () {

this.x  = "";

//Constructor
var Player = function() {
    // connect to the server
    this.x = "somevalue";
    this.socket  = io.connect();

};


Player.prototype = {
    constructor: Player,
    listen: function() {
     alert(this.x + " " + this.socket);           // fine get somevalue & [object, object]
     this.socket.on('event', function(data) {
        alert(this.x + " " + this.socket);        // this.x undefined this.socket [object, object]
        $.each(data, function(index,value) { 
           alert(this.x + " " + this.socket);     // undefined undefined  
        });
     });  
    }

return Player;
})();
4

1 回答 1

2

您的this事件和.each()回调函数与this您定义的地方xsocket. 当 Socket.io 库和 jQuery(分别)调用这些回调函数时this,通常会提供这些回调函数中的值。

为了解决这个问题,你的listen函数应该看起来更像:

listen: function() {
 var that = this; // <-- keep a reference to your module
 alert(that.x + " " + that.socket);           // fine get somevalue & [object, object]
 that.socket.on('event', function(data) {
    // in here, this could vary depending on the event
    alert(that.x + " " + that.socket);        // this.x undefined this.socket [object, object]
    $.each(data, function(index,value) { 
       // in here, this = the current data element
       alert(that.x + " " + that.socket);     // undefined undefined  
    });
 });  
}
于 2013-09-25T21:58:05.977 回答