Javascript闭包的创建方式

//Module模式闭包
var testModule = (function () {
    var count = 0;
    function privateMethod() { }

    return {//返回对象
        AddCount: function () {
            count++;
        },
        DesCount: function () {
            count++;
        },
        GetCount: function () {
            return count;
        },
        ResetCount: function () {
            count = 0;
        }
    };
})();

testModule.AddCount();
testModule.GetCount();

//另一种方式创建的闭包
(function () {
    var count=0;
    //直接给全局变量window添加成员
    window.GetCount=function(){
        return count;
    };
    window.AddCount=function(){
        count++;
    };
})();

AddCount();
GetCount();

posted @ 2018-10-08 15:57  skybirdzw  阅读(687)  评论(0编辑  收藏  举报