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
thattrickAnother possibility is explicitily binding the correct this to the callback function
The
thattrick 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.