回调函数中的javascript类变量作用域 [英] javascript class variable scope in callback function

查看:237
本文介绍了回调函数中的javascript类变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在Javascript中,为什么是这个”运算符不一致?

我有以下类:

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回调函数访问实例变量或函数吗?

How can I acces the instance variable or function from the connect callback function?

推荐答案

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

The simplest solution is to use the that trick

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;
});

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

Another possibility is explicitily binding the correct this to the callback function

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

技巧的优势在于可以根据需要嵌套到多个回调,并且绑定版本具有以下优点:允许你仍然在里面使用this。

The that trick has the advantage of nesting to as many callbacks as you want and the bind version has the advantage of allowing you to still use "this" inside.

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

A disadvantage of the bind method is that it is not supported in IE<=8 so you might need to use a shim if you need to support ancient browsers.

编辑:这个答案有点旧。现在您可能不再需要担心IE6了,您可能可以使用胖箭头语法,它不会覆盖这个

edit: This answer is a bit old. Nowadays you probably don't need to worry about IE6 anymore and you might be able to use fat arrow syntax, which doesn't overwrite the this.

这篇关于回调函数中的javascript类变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆