Sunday, October 14, 2012

javascript function scope sample

Javascript scope is used to enclose the internal logic and only expose the necessary public information to external. Basically, within a object or function scope, only properties or function  defined on the object are visible to external as public info through the object. Any local variables defined with var, or inner function are only available to internal logic.

var globalFunction = function () {    // global, can be accessed anywhere.
    alert('hello world');
}

var containerFunction = function () { // globale namespce, can be accessed anywhere.
   
    var subFunction = function () {    // private namespace method
        alert("I'm Private");
        globalFunction();              // We can access global Function here 2 levels deep.
    }
   
    containerFunction.test = function () {  //public namespace method
        alert("test");
    }

    callableFunc = function () {   //global method, because variable is global
        alert("callable");
    }

    function localFunc(){   //only visible to local
       alert("local");
    }

    varible ="8";  //unlike function, new varibles without var gets added to global window object

    globalFunction();                 // We can access global Function here 1 level deep.
    subFunction();                     // We can access subFunction inside containerFunction.
    localFunc();
    alert(varible);
}

containerFunction();
containerFunction.test();
callableFunc();
alert(varible);

//failure cases
//test();  //test is not visible in global scope
//subFunction(); //namespace private method and only exists inside containerFunction
//containerFunction.callableFunc(); //callableFunc is not belonging to namespace, it is global
//localFunc() //not visible

Note, unlike 

No comments:

Post a Comment