回调函数中的javascript类变量作用域

时间:2011-11-29 21:05:47

标签: javascript node.js

  

可能重复:
  In Javascript, why is the “this” operator inconsistent?

我有以下课程:

function Chat(some, nick, url) {
    this.socket = null;
    this.Nickname = nick;
    this.Url = url;

    this.Connect = function () {
        socket = io.connect(this.Url);
        socket.on('connect', function (data) {
            var p = this.Nickname; //this.Nickname is undefined why? 
            // how can I acess to the Nickname variable or function?
        }
    };
}

如何从connect回调函数访问实例变量或函数?

6 个答案:

答案 0 :(得分:28)

最简单的解决方案是使用that技巧

var that = this; //that is a normal variable
                 //so it is lexically scoped
                 //and can be used in inner functions

socket.on('connect', function(data){
    var p = that.NickName;
});

另一种可能性是将正确的this绑定到回调函数

socket.on('connect', function(data){
    var p = this.Nickname;
}.bind(this));

that技巧的优点是可以根据需要嵌套到尽可能多的回调,而绑定版本的优点是允许你仍然使用“this”。

绑定方法的一个缺点是IE< = 8不支持它,所以如果你需要支持古老的浏览器,你可能需要使用垫片。

编辑:这个答案有点旧。现在您可能不再需要担心IE6了,您可能可以使用fat arrow syntax,但不会覆盖this

答案 1 :(得分:2)

问题是javascript中的this值可能会根据调用回调的方式而改变。解决此问题的最简单方法是将原始this对象保存到名为self的本地对象中。本地在回调中捕获,可用于访问成员值。例如。

function Chat(some, nick, url) {
    var self = this;  
    this.socket = null;
    this.Nickname = nick;
            this.Url = url;

    this.Connect = function () {
        socket = io.connect(this.Url);
        socket.on('connect', function (data) {
            var p = self.Nickname; //this.Nickname is undifined why? 
             // how can I acess to the Nickname variable or function?
        }
    };
  }

答案 2 :(得分:2)

您可以更改此内容:var p = this.Nickname; 这个var p = nick;

您的问题是this是指您在回调中使用的函数的本地范围。这不是外部功能的范围。

答案 3 :(得分:1)

“this”代表你在该范围内的功能。

尝试:

function Chat(some, nick, url) {
    this.socket = null;
    this.Nickname = nick;
        this.Url = url;

    var that = this;

    this.Connect = function () {
        socket = io.connect(this.Url);
        socket.on('connect', function (data) {
            var p = that.Nickname; //this.Nickname is undifined why? 
            // how can I acess to the Nickname variable or function?
        }
    };
}

请注意将“this”分配到“that”

答案 4 :(得分:1)

JavaScript有闭包,至少可以说是漂亮的。

看看这个问题:

How do JavaScript closures work?

它应该可以帮助您理解为什么每个人都告诉您将var something = this放在函数上方并在其中使用something来维护对原始this的引用。

答案 5 :(得分:1)

这是一个小提琴,显示使用本地副本:

http://jsfiddle.net/k7vC6/1/

在这种情况下,thisself是相同的,但使用self是安全的。

相关问题