回调函数中的javascript类变量范围[重复]

时间:2023-02-12 09:56:24

Possible Duplicate:
In Javascript, why is the “this” operator inconsistent?

可能重复:在Javascript中,为什么“this”运算符不一致?

I have the following class:

我有以下课程:

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

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

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

6 个解决方案

#1


28  

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

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

socket.on('connect', function(data){
    var p = this.Nickname;
}.bind(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.

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

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.

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

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.

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

#2


2  

The problem is the this value in javascript can change depending on how the callback is invoked. The easiest way to work around this is to save the original this object into a local named self. The local is captured in the callback and can be used to access member values. For example.

问题是javascript中的这个值可能会根据调用回调的方式而改变。解决此问题的最简单方法是将原始此对象保存到名为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?
        }
    };
  }

#3


2  

You can change this: var p = this.Nickname; to this var p = nick;

你可以改变这个:var p = this.Nickname;这个var p = nick;

Your problem is that this refers to the local scope of the function you are using in the callback. It's not the scope of the outer function.

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

#4


1  

JavaScript has closures which are, to say the least, nifty.

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

Have a look at this question:

看看这个问题:

How do JavaScript closures work?

JavaScript闭包如何工作?

It should help you understand why everyone is telling you to put a var something = this above the function and use something inside of it to maintain a reference to the original this.

它应该可以帮助你理解为什么每个人都告诉你在函数上面放置一个var = this并使用它内部的东西来保持对原始函数的引用。

#5


1  

Here's a fiddle that shows using the local copy of this:

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

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

In that instance, this and self are the same thing, but using the self is safe.

在那种情况下,这和自我是一回事,但使用自我是安全的。

#6


1  

"this" is representing your function in that scope.

“this”表示您在该范围内的功能。

try :

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

Note the assignment of "this" into "that"

注意将“this”赋值为“that”

#1


28  

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

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

socket.on('connect', function(data){
    var p = this.Nickname;
}.bind(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.

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

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.

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

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.

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

#2


2  

The problem is the this value in javascript can change depending on how the callback is invoked. The easiest way to work around this is to save the original this object into a local named self. The local is captured in the callback and can be used to access member values. For example.

问题是javascript中的这个值可能会根据调用回调的方式而改变。解决此问题的最简单方法是将原始此对象保存到名为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?
        }
    };
  }

#3


2  

You can change this: var p = this.Nickname; to this var p = nick;

你可以改变这个:var p = this.Nickname;这个var p = nick;

Your problem is that this refers to the local scope of the function you are using in the callback. It's not the scope of the outer function.

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

#4


1  

JavaScript has closures which are, to say the least, nifty.

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

Have a look at this question:

看看这个问题:

How do JavaScript closures work?

JavaScript闭包如何工作?

It should help you understand why everyone is telling you to put a var something = this above the function and use something inside of it to maintain a reference to the original this.

它应该可以帮助你理解为什么每个人都告诉你在函数上面放置一个var = this并使用它内部的东西来保持对原始函数的引用。

#5


1  

Here's a fiddle that shows using the local copy of this:

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

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

In that instance, this and self are the same thing, but using the self is safe.

在那种情况下,这和自我是一回事,但使用自我是安全的。

#6


1  

"this" is representing your function in that scope.

“this”表示您在该范围内的功能。

try :

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

Note the assignment of "this" into "that"

注意将“this”赋值为“that”