CommonJS 和 AMD 規范?
1. 什么是CommonJS?
CommonJS 是javascript模塊化編程的一種規范,主要是在服務器端模塊化的規范,一個單獨的文件就是一個模塊。每一個模塊都是一個單獨的作用域,也就是說,在該模塊內部定義的變量,無法被其他模塊讀取,除非定義為global對象的屬性。
在CommonJS中有一個全局性方法require( ),用于加載模塊。
//example.js
module.exports = function( ){ };
example.message = "hi";
//main.js
var example = require("./example");
CommonJS加載模塊是同步的,只有加載完成,才能執行后面的操作,主要是由于服務端的編程模塊文件都存在于本地硬盤,所以加載較快。
2. 什么是AMD 規范?
AMD是"Asynchronous Module Definition"的縮寫,意思就是"異步模塊定義"。異步方式加載模塊,模塊的加載不影響它后面語句的執行。所有依賴這個模塊的語句,都定義到一個回調函數中,等到加載完成之后,這個回調函數才會運行。
AMD規范使用define方法定義模塊:
define(["/libs/jquery"], function(jquery){
function log(){
alert("hello world!");
}
return {
log: log
}
});
當然AMD也允許輸出模塊兼容CommonJS規范:
define(function(require, exports, module){
var module = require("module");
module.doSometing( );
exports.do = function(){
module.doSometing( );
}
});