Tuesday, October 23, 2012

Variable spilling in global space

Let's say you have defined members using "this" within a function. Instead of constructing an object from this function you use it as a regular function call. What should happen here? In this case we are not calling the function with a specific context, hence all the objects defined by "this" will be created under the scope where this function call is made.

Example,

function Person()
{
    this.name = "XYZ"
    this.address = "Somewhere"
    
    this.displayPerson = function(){
        alert(this.name + " lives at " + this.address);
    }
}

// Call it as normal function instead of constructor using new
Person();

// members defined by "this" are available in current scope
console.log(name);
console.log(address);
console.log(displayPerson);

Monday, October 22, 2012

Calling a function with different context in JavaScript

In JavaScript it is possible to call a function with different context, i.e. a different object instead of the object of the defining function. We can think of context as scope. So the question is what happens when we change the context when calling a function?

When we call a function in a standard way everything in that function is executed under the default scope. And all the variables (or objects) are created under the scope of that function object (remember function is also an object in JS). So when we call a function with different context, everything executed in that function assumes new scope and everything is created in this new scope.

Here is a very simple example that illustrates what happens when we change function's execution context:

function createMsg(msg){
    finalMsg = "ControlRoom:: " + msg;
    return finalMsg;
}

function displayMyMsg(){
   // change the scope by using Function.call
   //   and scope is changed to current function object by passing "this"
   createMsg.call( this, "Welcome to the world of JS!" );
   // Now we have finalMsg variable (from createMsg) available to use
   alert( finalMsg );
}

displayMyMsg();

This technique is called "Delegation" since we are delegating execution scope to a different object. This technique can also be used with constructor functions allowing us to create a kind of inheritance.

Check out this great article by Angus Croll to understand the use of this technique.