一 Commonjs
一開始js是垃圾,但隨着時代的發展、業務的進步,js變得愈來愈重要,但js涉及之初就是用來打雜的,有缺陷以下:html
- 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.
- 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.
- JavaScript has no standard interfaces for things like Web servers or databases.
- 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
- 沒有模塊系統
- 沒有標準庫、沒有文件、沒有IO系統
- 沒有標準接口,用來作服務器、或者數據庫
- 沒有依賴包管理系統。
因此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中會天然採用嚴格模式:
- 變量必須聲明後再使用
- 函數的參數不能有同名屬性,不然報錯
- 不能使用with語句
- 不能對只讀屬性賦值,不然報錯
- 不能使用前綴0表示八進制數,不然報錯
- 不能刪除不可刪除的屬性,不然報錯
- 不能刪除變量delete prop,會報錯,只能刪除屬性delete global[prop]
- eval不會在它的外層做用域引入變量
- eval和arguments不能被從新賦值
- arguments不會自動反映函數參數的變化
- 不能使用arguments.callee
- 不能使用arguments.caller
- 禁止this指向全局對象
- 不能使用fn.caller和fn.arguments獲取函數調用的堆棧
- 增長了保留字(好比protected、static和interface)
參考:http://www.cnblogs.com/chengu...