JavaScript中的模块化

1.原始写法(函数)
 function m1(fn){
           return fn;
      };

      function m2(x){
           return x+1
      };

      document.write(m1(m2(2)));

这种写法会污染全局变量,无法保证不与其它模块发生命名冲突,而且无法直接看出模块成员之间的关系

2.对象
//将函数放入对象里面
 const module1 = {
          count:0,
          increase:function(){
              this.count++
          },
          decrease:function(){
              this.count--
          }
      }
      module1.increase();
      module1.decrease();
      module1.count=100;
      console.log(module1.count);//100

这种写法将对象直接导出,对象的属性可以直接被篡改//module1.count=0

3.立即执行函数
const module2=(function(){
        var count=0;
        const increase=function(){
           count++;
        };
        const decrease = function(){
          count--;
        }

        const getCount=function(){
            return count;
        }
      return {
          increase,
          decrease,
          getCount
      }
      })()

      console.log(module2.count);//undefined
      module2.increase();
      console.log(module2.getCount());//1

//缺点:无法直接访问模块的变量,必须通过暴露方法getCount来访问count

4.放大模式 (立即执行函数升级版)
 var myModule={
          count:0,
          increase:function(){
              this.count++;
              return this.count;
          },
          decrease:function(){
               this.count--;
               return this.count;
          }

      }

     
    myModule=(function(module){
        console.log(module,6666)
        module.setVal =function(value){
            module.count=value;
        };
        return module;
    })(window.myModule);
    //注意这里如果直接写myModule 会报ReferenceError 
    myModule.setVal(200);
    console.log(myModule.count);//200

//这种写法在各种工具库的源码中随处可见

6. ES6 module
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值