javascript模块化开发初探

//immediately-invoked fuction expression   iife
;(function(arg){
    return something;
})(arg);
//第二种写法 
!function(arg){

}(arg);

//第三种写法
(function(arg){

}(arg));
 
//eg 可访问ModuleProperty moduleMethod
    var Module = (function(){
        var my = {},
            privateVariable = 1;
        function privateMethod(){

        }
        my.ModuleProperty = 1;
        my.moduleMethod = function(){

        };
        return my;
    }());

//eg2
    var Module = (function(){
        var my = {},
            privateVariable = 1;
        function privateMethod(){

        }
        my = {
            ModuleProperty : 1;
            moduleMethod : function(){

            }
        }
        return my;
    }());

    //使用对象直接量来表达
    var my = {
            ModuleProperty : 1;
            moduleMethod : function(){

            }
        };
    //返回一个函数 如jquery
    var Cat = (function(){
        //    私有成员
        return function(name){
            this.name = name;
            this.bark = function(){};
        }
    }());
    var tomcat = new Cat("tom");
    tomcat.bark();
//
    var module =(function(){
        var x = 1;
        function f1(){}
        function f2(){}
        return {
            publicmethod : f1,
            publicmethod : f2
        }

    }());

    //扩展
    var Module = (function(my){
        my.anothermothod = function(){

        };
        return my;
    }(Module));

    //松耦合扩展  如果没有定义过Module 或者不在乎加载顺序的话
     var Module = (function(my){
         my.anothermothod = function(){

        };
        return my;
     }( Module || {} ));

     //紧耦合扩展   定义过,并且在以前的基础上扩展 覆盖已有方法
      var Module = (function(my){
          var oldmothod = my.modulemethod;
          my.modulemethod = function(){
              //方法重载
          };
        return my;
     }( Module ));

     //克隆与继承     a
     var module_two = (function(old){
         //
         var my = {},
             key;
         for( key in old ){
             if(old.hasOwnPropery(key)){
                 my[key] = old[key]
             }
         }
         
         var supermethod = old.modulemethod;
         my.modulemethod = function(){
             //重写
             //supermethod
         };
     }(Module));
     // b   Create(old);
     var module_two = (function(old){
         
         var my = Create(old);

         var supermethod = old.modulemethod;
         my.modulemethod = function(){
             //重写
             //supermethod
         };
     }(Module));

 

posted @ 2014-11-06 18:44  FaithJin  阅读(153)  评论(0编辑  收藏  举报