【问题标题】:Javascript Object : instance variable scopeJavascript 对象:实例变量范围
【发布时间】:2013-10-01 16:33:17
【问题描述】:

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

在listen 函数中,实例变量在第一个警报时正确定义。 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;
})();

【问题讨论】:

  • 好吧,一方面,您希望this 在外部匿名函数上下文中引用什么?如果您处于“严格”模式,它将是 window(全局对象)或 undefined
  • 来自 Java 和 C++,您对 this 的行为方式有着截然不同的期望。我发现这是对 Javascript 不同之处的一个很好的推动:bonsaiden.github.io/JavaScript-Garden
  • JavaScript this 与 Java 的 this非常不同。此外,x 不是“变量”,而是对象的属性
  • @Bergi 我现在知道了。你可以调用 x 任何你喜欢的属性、属性、变量取决于你使用的语言...
  • @avrono:不在 JS 中,[local] variable(在范围内)和 property /attribute/slot/ 之间有一个重要区别随便什么(在一个物体上)。

标签: javascript jquery oop socket.io scope


【解决方案1】:

事件中的this.each() 回调函数与定义xsocketthis 不同。当 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  
    });
 });  
}

【讨论】:

  • 感谢您的及时回复。显然,我没有正确地考虑过这一点。现在一切都说得通了……
  • @avrono:不客气!这是一件很容易忘记的事情。请注意,this 可能会根据使用它的上下文而改变。
猜你喜欢
  • 2013-05-29
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多