Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  18] [ 6]  / answers: 1 / hits: 16366  / 13 Years ago, tue, november 29, 2011, 12:00:00

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?


More From » node.js

 Answers
20

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.


[#88842] Monday, November 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maximusbradforde

Total Points: 594
Total Questions: 106
Total Answers: 82

Location: Tuvalu
Member since Sat, Feb 11, 2023
1 Year ago
;