js模块化 javascript 模块化 闭包写法 闭包模块化写法

var main = main || {};

    ; (function (main) {
        'use strict';

        //私有变量
        var _s1 = 'Hello ';
        var _s2 = 'World!~';

        //私有方法
        var _func = {
            helloWorld: function (str1, str2) {
                return str1 + str2;
            }
        };

        //公有方法
        main.method = {
            add: function (a, b) {
                return a + b;
            },
            subtract: function (a, b) {
                return a - b;
            },
            multiply: function (a, b) {
                return a * b;
            },
            divide: function (a, b) {
                return a / b;
            },
            total: function (a, b) {
                return _func.helloWorld(_s1, _s2) + this.add(a, b) + this.subtract(a, b) + this.multiply(a, b) + this.divide(a, b);
            }
        };

        //将公有方法返回
        return main.method;
        
    })(main);

    var t = main.method.total(1, 1);
    console.log(t);///"Hello World!~2011"

实例 :

原文地址:https://www.cnblogs.com/lguow/p/10791837.html