Skip to content Skip to sidebar Skip to footer

Javascript Class Variable Scope In Callback Function

Possible Duplicate: In Javascript, why is the “this” operator inconsistent? I have the following class: function Chat(some, nick, url) { this.socket = null; this.Nic

Solution 1:

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.

Solution 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.

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

Solution 3:

You can change this: var p = this.Nickname; to this 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.

Solution 4:

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

Have a look at this question:

How do JavaScript closures work?

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.

Solution 5:

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.

Post a Comment for "Javascript Class Variable Scope In Callback Function"