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);

No comments:

Post a Comment