Javascript scope chain example

Scope chain is a very important part in javascript.  The best way to understand it is code example. Code below is collected from internet and my memory.

// a globally-scoped variable
var a=1;

// global scope
function one(){
    alert(a); 
}

one();

// local scope
function two(a){
    alert(a);
}

two(2);

// local scope again
function three1(){
  var a = 3
  alert(a); 
}

three1();

// local scope again
function three2(){
  alert(a); // alerts "undefined", curz local "a" is defined in local scope already,but not defined when alert()
  var a = 3;
}

three2();

// Intermediate: no such thing as block scope in javascript

function four1(){
     if(true){
        var a=4;
    }
     alert(a); // alerts '4', not the global value of '1'
}

four1();

function four2(){
    alert(a); // alerts 'undefined',same reason as that of three2();
     if(true){
        var a=4;
    }
}

four2();

// Intermediate: object properties
function Five(){
    this.a = 5;
}

alert(new Five().a);



// Advanced: closure
var six = function(){
    var foo = 6;
    return function(){
        // javascript "closure" means I have access to foo in here, 
        // because it is defined in the function in which I was defined.
        alert(foo);
    }
}()

six();


// Advanced: prototype-based scope resolution
function Seven(){
  this.a = 7;
}

// [object].prototype.property loses to [object].property in the scope chain
Seven.prototype.a = -1; // won't get reached, because 'a' is set in the constructor above.
Seven.prototype.b = 8; // Will get reached, even though 'b' is NOT set in the constructor.

alert(new Seven().a);
alert(new Seven().b);


function Night(){
  this.a = 9; 
  alert(a);
}

Night();//if dont instantiate Night then this is actually current context----window. 
alert(a);// So if this.a is changed in Night(),then the global a is changed as well.
  • #23001 web
    2011-01-06 05:26

    Very helpful