Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript class variable scope in callback function [duplicate]

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?

like image 551
elranu Avatar asked Nov 29 '11 21:11

elranu


1 Answers

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.

like image 166
hugomg Avatar answered Oct 19 '22 23:10

hugomg