js模块化学习笔记一

一、模块化的理解

什么是模块?

将一个复杂的程序依据一定的规则(规范)封装成几个块(文件),并将其组合在一起。其中,块的内部数据/实现是私有的,只是向外部暴露一些接口(方法)与外部其他模块通信。

一个模块的组成

由内部变量、内部函数组成,向模块外部提供N个行为。对模块外部而言,内部变量和内部函数皆属于私有数据和私有行为。

什么是模块化?

描述一种特别的编码项目JS的方式:以模块为单元一个一个编写的模块化的项目:JS编码时是按照模块一个一个编码的。

二、模块化的进化过程

1.全局function模式

编码:全局变量/函数
问题:污染全局命名空间,容易引起命名冲突/数据不安全;
案例:

  • module1.js
let data = 'heiyuedu.com'
function foo(){
    console.log('foo() ${data}')
}
function bar(){
    console.log('bar() ${data}')
}
  • module2.js
 let data2 = "other data";
function foo(){
    console.log('foo() ${data2}')
}
  • Test1.html



2.namespace模式

编码:将数据/行为封装到对象中
解决:命名冲突(减少了全局变量)
问题:数据不安全(外部可以直接修改模块内部的数据)
案例:

  • module1.js
let myModule = {
    data : 'heiyuedu.com',
    foo(){
        console.log('foo() '+this.data);
    },
    bar(){
        console.log('bar() '+this.data);
    }
}
  • Module2.js
let myModule2 = {
    data : 'heiyuedu.com2',
    foo(){
        console.log('foo() '+this.data);
    },
    bar(){
        console.log('bar() '+this.data);
    }
}
  • Test2.html



3.IIFE模式

IIFE:立即调用函数表达式--->匿名函数自调用
编码:将数据和行为封装到一个函数内部,通过给window添加属性来暴露接口;
引入依赖:通过函数形参来引入依赖模块
作用:数据是私有的,外部只能通过暴露的方法操作
问题:如果当前这个模块依赖另一个模块怎么办?
案例:

  • module3.js
(function(window){
    let data = 'heiyuedu.com'
    function foo(){//用于暴露的函数
        console.log('foo():'+this.data);
    }
    function bar(){
        console.log('bar():'+this.data);
        otherFunc();
    }
    function otherFunc(){//内部私有的函数
        console.log("otherFunc()");
    }
    //暴露行为
    window.myModule = {foo,bar}
})(window)
  • Test3.html


4.IIFE模式增强

引入依赖,比如引入JQuery
案例:

  • module4.js
(function(window,\$){
    let data = 'heiyuedu.com'
    function foo(){
        console.log('foo()'+data);
        $('body').css('background','red');
    }
    function bar(){
        console.log('bar()'+data);
        otherFunc();
    }
    function otherFunc(){
        console.log('otherFunc()');
    }
window.myModule = {foo,bar}
})(window,jQuery)
  • Test4.html



  
  04_IIFE模式增强







你可能感兴趣的:(js模块化学习笔记一)