[Javascript] Global import

/**
    Global Imports
*/
var wartime = true;
var ARMORY = (function(){{
    //add var to the private properties
    var weaponList = [*list of weapon objects*]; //private
    var armorList = [*list of armor objects*];  //private
    
    var removeWeapone = function(){};  //private
    var replaceWeapon = function(){};  //private
    var removeArmor = function(){};    //private
    var replaceArmor = function(){};   //private    

    return{
        makeWeaponRequest = function(){
            if(wartime) //let civilian have weaponry
        };  //public
        makeArmorRequest = function(){};  //public    
    };    
})();

/*#1: When non-local variables are referenced in a module, the
entire length of the scope chain is checked.*/
//wartime will be check throughout the module, a very expensive process 
//if there is any namespace depth and / or multipe references.

/*#2: Lengthy namespaces mean that global variable have unclear scope,
leading to code that is tought to manage.*/

/**
    For clearer, faster globals in modules, use imports
*/
var ARMORY = (function( war ){{
    //add var to the private properties
    var weaponList = [*list of weapon objects*]; //private
    var armorList = [*list of armor objects*];  //private
    
    var removeWeapone = function(){};  //private
    var replaceWeapon = function(){};  //private
    var removeArmor = function(){};    //private
    var replaceArmor = function(){};   //private    

    return{
        makeWeaponRequest = function(){
            if( war ) //let civilian have weaponry
        };  //public
        makeArmorRequest = function(){};  //public    
    };    
})(wartime); //pass all you globals into your IIFE using calling parentheses. IMPORTS!


/**
    In summary:
    Your import ensures clarity of scope within a module.
    By using a parameter, you protect the global data that might have been overwritten.
    All imported data becomes locally scoped to the anonymous function, to be used in closure.
    Thus, when compared with searching the entire scope chain, imports are both clearer and faster
*/

 

posted @ 2014-08-17 20:30  Zhentiw  阅读(260)  评论(0)    收藏  举报