Friday, July 12, 2013

var that=this in Javascript

If you have ever saw or read any open-source library in Javascript, I can assure you at least in one part of the code, you will see something like following:
var that = this;
You may wonder why is that so? Well, in short answer it is because of how Javascipt defined its scope. In many modern programming languages the type of scope is a block scope. In block scope, everything which is wrapped inside a curly brace will not be visible outside of the braces. In Javascript, it is functions scope. What does that mean? It means that a scope unit in defined within function, and all variables which are defined within the function are not accessible outside of that function. In Javascript it is very common that you define a function inside a function, whether that is a function of an object literal, or closures. Actually the case with our case mainly happens within such case.

Ok, So let us consider a very common case in Javascript programming. Let us say that you have created an object literal:

var person = {
 id : 1
}; 

Now let us say that you need to augment that object literal. Here, we are trying to do this:

person.augmentInfo = function () {
   var setNewId = function () {
    
   // this here does not refer to the person context, but rather to setNewId function
   // therefore the following line cannot set the new Id 
           
   this.id = 3;
 }

 setNewId();
};

Now if you check whether new id has been set or not, you see that it has not! Check the following lines yourself:
myObject.augmentInfo();
console.log(myObject.id); //undefined is logged

So basically the reason why we use that notation is when going inside a new scope zone, you can save the value of this in the outter scope to be able to access variables and methods in the outter context from the inside context.


person.augmentInfo = function ()
{
        var that = this;
        
        var setNewId = function () {
    
            // this here does not refer to the person context, but rather to setNewId function
            // therefore the following line cannot set the new Id 
           
            that.id = 3;
        }

        setNewId();
};

Now if you verify it, you can see that right now, the newId is being set corrently.

myObject.augmentInfo();
console.log(myObject.id); //3 is logged, correctly

1 comment: