> For the complete documentation index, see [llms.txt](https://coffe1891.gitbook.io/frontend-hard-mode-interview/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coffe1891.gitbook.io/frontend-hard-mode-interview/id-1/2.-he-xin-gai-nian/1.2.14.md).

# 壹.2.14 模块化开发

一线互联网公司几乎都在推行模块化开发

## 壹.2.14.1 老一辈前端工程师如何实现模块化

在 ECMAScript 6 出现之前，JavaScript语言没有内建支持模块化的语法，这导致前端开发复杂Web应用的时候，引用.js、组织文件、扩展功能、维护工程都显得效率低下，而且流程繁琐。然而对于一个复杂的Web应用，模块化编程可以良好的工作分工、功能扩展、工程维护，是软件开发方法论里面最基本的需求。那时候老一辈前端工程师们可以使用 IIFE 函数来实现模块化，很多库比如jQuery是这样实现的。

```javascript
let module = (function() {
    var _version = "1.0"; 
    var _name = "a-nice-module";

    function _log(x) {
        console.log(x);
    }

    function say(s) {
        _log(s);
    }

    return {
        name: _name,
        say: say
    };
})();

console.log(module._version);//>> undefined
console.log(module._log);//>> undefined
console.log(module.name); //>> a-nice-module
module.say("hello"); //>> hello
```

**模块本质上是封装，把模块内可访问的和不可以访问的区分得清清楚楚**。如上示例，模块之外是无法访问到模块内部的私有属性`_version`和私有方法`_log`的；而以一个对象的属性和方法的形式暴露内部属性`_name`和方法`say(s)`之后，然后将该对象返回给模块外部的调用者，那么在模块外部就可以访问它们了。

ECMAScript 6 吸收了老一辈前端工程师的各种优秀思想，最终采用了`import`和`export`内建语法支持模块化开发，基于浏览器底层的实现，使前端的模块化开发变得空前地规范和有效率起来，模块化开发终于迎来了应用热潮。

## 壹.2.14.2 AMD 和 CommonJS

//todo

## 壹.2.14.3 ECMAScript 6 的模块化

### 1.模块里的变量是以引用形式传递的

模块内变量的改变会同步到外面，说明是模块是以引用类型传递的，也即引用模块时，模块外层再包了一层对象，变量以该对象的属性传递过去。举例说明如下：

```javascript
///////////////// module.js //////////////////////

let m = 0;
setTimeout(() => {
  m = 1;
}, 1000);
export function getM() {
  return m;
}
```

上面代码相当于传递下面的对象，其中\_m表示私有属性m

```javascript
{
  _m:0,
  getM:function(){
    return this._m;
  }
}
```

下面为入口文件 index.js ：

```javascript
/////////////// index.js //////////////////////////

import {getM} from "./module.js";
setTimeout(()=>{
    console.log(getM());
});
setTimeout(()=>{
    console.log(getM());
},2000);
//>> 0
//>> 1
```

### 2.模块嵌套

有些书籍称之为模块的继承，继承是面向对象编程的概念，本书更愿意称之为**嵌套**。

//todo
