JavaScript中模块模式的应用

模块模式是JavaScript中使用最广泛的模式,模块利用了闭包的特性
Module模式的基本特征:

  1. 模块化,可重用
  2. 封装了变量和function,和全局的namaspace不接触,松耦合
  3. 只暴露可用public的方法,其它私有方法全部隐藏
//自执行函数(immediately invoked function)
(function(){
}());
//这样也可以(this works too)
(function(){})();
//增加参数(add params to first)
(function(my){
}(variable));
//增加返回值(add return)
(function(my){//
    return my;
}(variable));
//这样MODULE就是返回的my(give my to MODULE)
//js加载完就会运行这个函数,并且把返回值赋予MODULE
var MODULE = (function(my){//
    return my;
}(variable));
//把自执行函数的参数换成返回的变量(change immediately invoked function parameter)
var MODULE = (function(my){//
    return my;
}(MODULE || {}));
//你可以在其他任意地方这样定义MODULE
//所有的方法都会可以用MODULE来调用
//now you can define MODULE anywhere you like,
//all the functions inside will be extended to others
// 增加功能(add capabilities)
var MODULE = (function (my) {
    //you cannot access inner variable
    var variable = {};
    // this is inner function, you cannot call it outside of the MODULE
    function innerFun(){
        console.log(variable);//you can access inner variable here
    }
    //this function will be exported, you can call it outside
    my.someFun = function(){
        //you can call inner variable and function here
        console.log(variable);
        innerFun();
    };
    return my;
}(MODULE || {}));
//MODULE || {} is the parameter passed to this MODULE,
//equals "my" inside MODULE
//you can define MODULE anywhere else

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注