对象编程和模块编程

33 阅读1分钟

传统的是这样

var current = null;
var labels = {
    'home':'home',
    'articles':'articles',
    'contact':'contact'
};
function init(){
};
function show(){
    current = 1;
};
function hide(){
    show();
};

对象的写法这样

demo = {
    current:null,
    labels:{
        'home':'home',
        'articles':'articles',
        'contact':'contact'
    },
    init:function(){
    },
    show:function(){
        demo.current = 1;
    },
    hide:function(){
        demo.show();
    }
}

模块化的是这样

module = function(){
    var labels = {
        'home':'home',
        'articles':'articles',
        'contact':'contact'
    };
    return {
        current:null,
        init:function(){
        },
        show:function(){
            module.current = 1;
        },
        hide:function(){
            module.show();
        }
    }
}();

优化后是这样

module = function(){
    var current = null;
    var labels = {
        'home':'home',
        'articles':'articles',
        'contact':'contact'
    };
    var init = function(){
    };
    var show = function(){
        current = 1;
    };
    var hide = function(){
        show();
    }
    return{init:init, show:show, current:current}
}();
module.init();
//模块模式最流行的闭包类型之一,它允许你模拟公共的、私有的、和特权成员
        //模块建议用这个
        var Module = (function() {
            var privateProperty = 'foo';
            function privateMethod(args) {
                // do something
            }
            return {
                publicProperty: '',
                publicMethod: function(args) {
                    // do something
                },
                privilegedMethod: function(args) {
                    return privateMethod(args);
                }
            };
        })();
        //插件可以考虑用这个
        var Moudle2 = (function() {
            var init = function(arg) {
                this.arg = arg;
                this.getArg();
                console.log("111111")
            }
            init.prototype.show = function() {
            }
            init.prototype.getArg = function() {
                return this.arg;
            }
            init.prototype.hide = function() {
            }
            return init;
        })();
        console.log(new Moudle2("55"));

对于业务代码可以这样组织