Javascript的模块管理 CMD AMD ES7等

一 Commonjs

一开始js是垃圾,但随着时代的发展、业务的进步,js变得愈来愈重要,但js涉及之初就是用来打杂的,有缺陷以下:html

  1. JavaScript has no module system. To compose JavaScript scripts, they must be either managed in HTML, concatenated, injected, or manually fetched and evaluated. There is no native facility for scope isolation or dependency management.
  2. JavaScript has no standard library. It has a browser API, dates, and math, but no file system API, much less an IO stream API or primordial types for binary data.
  3. JavaScript has no standard interfaces for things like Web servers or databases.
  4. JavaScript has no package management system that manages dependencies and automatically installs them, except JSAN (not to be confused with JSON), which falls short for scope isolation.

简单翻译下:node

  1. 没有模块系统
  2. 没有标准库、没有文件、没有IO系统
  3. 没有标准接口,用来作服务器、或者数据库
  4. 没有依赖包管理系统。

因此mozila的工程师但愿来解决这个问题数据库

“What I’m describing here is not a technical problem. It’s a matter of people getting together and making a decision to step forward and start building up something bigger and cooler together.”浏览器

这并非一个技术问题,而是为了便于更多人合做...服务器

因此就有了commonjs,定义了这些概念,而nodejs实现了这个标准。
CommonJS定义的模块分为:{模块引用(require)} {模块定义(exports)} {模块标识(module)}
好比这个样子:less

// foo.js
module.exports = function(x) {
  console.log(x);
};

// main.js
var foo = require("./foo");
foo("Hi");

看似完美的解决了模块问题,但在浏览器模式下是不行的,假设咱们有以下这段代码异步

var math = require('math');
math.add(2, 3);

问题1:math.add会被阻塞掉,必须在require完成以后再执行
问题2:即便可以异步加载,但你如何可以知道何时加载完毕,何时可以执行完么?函数

二 AMD

(Asynchronous Module Definition) 异步模块加载
这里不得不说到咱们的requirejs,它有两个参数 
 requirejs

require([module], callback);

第一个表示依赖的模块,第二个就是具体的回掉了,好比上上述的代码fetch

require(['math'], function (math) {
    math.add(2, 3);
  });

三 ES6

ES6中的模块最大的特色就是静态,即在编译时就肯定依赖关系,ES6中会天然采用严格模式:

  1. 变量必须声明后再使用
  2. 函数的参数不能有同名属性,不然报错
  3. 不能使用with语句
  4. 不能对只读属性赋值,不然报错
  5. 不能使用前缀0表示八进制数,不然报错
  6. 不能删除不可删除的属性,不然报错
  7. 不能删除变量delete prop,会报错,只能删除属性delete global[prop]
  8. eval不会在它的外层做用域引入变量
  9. eval和arguments不能被从新赋值
  10. arguments不会自动反映函数参数的变化
  11. 不能使用arguments.callee
  12. 不能使用arguments.caller
  13. 禁止this指向全局对象
  14. 不能使用fn.caller和fn.arguments获取函数调用的堆栈
  15. 增长了保留字(好比protected、static和interface)

参考:http://www.cnblogs.com/chengu...

相关文章
相关标签/搜索