Sunday, October 23, 2011

JavaScript: Objects and the this keyword

Right now, I'm developing a complex jQuery plugin with a bunch of objects. Most of the these are connected together somehow in each others' definition. In one of these objects, the this keyword referenced to another object and I was not able to find a variable related to my object. The reason was I had to call one of its function in another context and with another this object. Here is the example:

var obj = function() {

    /* Private variables */ 
    var v1 = 0;
    var v2 = 0;
    
    /* Public variables */ 
    this.state = false;

    /* Public functions */
    this.update = function() {
       if(this.state) do_stuff();

       console.log(this.state); // undefined!!!
    }

};

So, when when I called the update function in another context with another this object, the this keyword referenced to the caller object, not to the object where it was. The result of this is that the state variable is undefined, because the caller object didn't have a state variable. I knew that the this keyword is the problem and I also knew that I need to reference to the object in its own functions. So the solution is to create a private variable and store a reference to the object in it.

var obj = function() {

    /* Reference to self */
    var _self = this;

    /* Private variables */ 
    var v1 = 0;
    var v2 = 0;
    
    /* Public variables */ 
    _self.state = false;

    /* Public functions */
    _self.update = function() {
       if(_self.state) do_stuff();

       console.log(_self.state); // false

       this.somethingElse = true;
    }

};

With this solution, if you create an object with the new keyword, the constructor is called and the _self variable will store a reference to itself. This won't mess up the this reference in other contexts.

No comments:

Post a Comment