Possible Duplicate:
In Javascript, why is the “this” operator inconsistent?
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?
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));
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With