使用闭包构建模块

 

 

var gLanuageName  = "javaScript";
    function func(){
        var a = 2;
        if(a === 2){
            var b = 3;
        }
        alert(b);//函数func作用域

        var funcDouble  = function(){
            return 2 * a;//闭包作用域中找到了a
        };
        (function(){
            alert(gLanuageName );//全局作用域中找到gLangualgeName
        })();

        return funcDouble;
    }
    var funcDouble1 = func();
    alert(funcDouble1());

 

var oCounter = (function(){
        var  i = 0;
        var get = function(){
            return i;
        };
        var add = function(){
            i++;
            return i;
        }
        var sub = function(){
            if(i - 1 < 0){
                alert("counter is zero. Cannot perfrom subtraction.");
                return i;
            }
            i--;
            return i;
        }
        var o = {
            get: get,
            add: add,
            sub: sub
        }
        return o;
    })();
    oCounter.add();
    alert(oCounter.get());
    oCounter.sub();
    alert(oCounter.get());
    oCounter.sub();
    alert(oCounter.get());

 

posted @ 2015-08-14 15:05  darr  阅读(209)  评论(0编辑  收藏  举报