標籤:var pen 請求 依賴 ret 函數 返回 上下文 cti
1 //CommonJS模組規範, 2 //每個模組存在著require、exports、module 這3個變數,nodejs對擷取的js檔案內容進行了頭尾封裝 3 (function (exports, require, module, __filename, __dirname) { 4 var math = require(‘math‘); 5 exports.area = function (radius) { 6 return Math.PI * radius * radius; 7 }; 8 }); 9 10 //AMD(Asynchronous Module Definition)規範是CommonJS規範延伸,11 //https://github.com/amdjs/amdjs-api/wiki/AMD12 //模組定義如下define(id?, dependencies?, factory); 它的模組id和依賴是可選的,13 //第一個參數 id 為字串類型,表示了模組標識,為選擇性參數。若不存在則模組標識應該預設定義為在載入器中被請求指令碼的標識。如果存在,那麼模組標識必須為頂層的或者一個絕對的標識。14 //第二個參數,dependencies ,是一個當前模組依賴的,已被模組定義的模組標識的數組字面量。15 //第三個參數,factory,是一個需要進行執行個體化的函數或者一個對象。16 17 //建立模組標識為 alpha 的模組,依賴於 require, export,和標識為 beta 的模組 18 define("alpha", [ "require", "exports", "beta" ], function( require, exports, beta ){19 export.verb = function(){20 return beta.verb();21 // or:22 return require("beta").verb();23 }24 });25 26 //一個返回對象字面量的非同步模組27 define(["alpha"], function( alpha ){28 return {29 verb : function(){30 return alpha.verb() + 1 ;31 }32 }33 });34 35 //無相依模組可以直接使用對象字面量來定義36 define( {37 add : function( x, y ){38 return x + y ;39 }40 } );41 42 //類似與 CommonJS 方式定義43 define( function( require, exports, module){44 var a = require(‘a‘),45 b = require(‘b‘);46 47 exports.action = function(){};48 } );49 50 define(function() { 51 var exports = {}; 52 exports.sayHello = function() { 53 alert(‘Hello from module: ‘ + module.id); 54 }; 55 return exports; 56 }); 57 58 define([‘dep1‘, ‘dep2‘], function (dep1, dep2) { 59 return function () {}; 60 }); 61 62 63 //CMD(Common Module Definition)規範64 define(function(require, exports, module) { 65 // The module code goes here 66 }); 67 68 相容多種模組規範69 ;(function (name, definition) { 70 // 檢測上下文環境是否為AMD或CMD 71 var hasDefine = typeof define === ‘function‘, 72 // 檢查上下文環境是否為Node 73 hasExports = typeof module !== ‘undefined‘ && module.exports; 74 75 if (hasDefine) { 76 // AMD環境或CMD環境 77 define(definition); 78 } else if (hasExports) { 79 // 定義為Node模組 80 module.exports = definition(); 81 } else { 82 // 將模組的執行結果掛在window變數中,在瀏覽器中this指向window 對象 83 this[name] = definition(); 84 } 85 })(‘hello‘, function () { 86 var hello = function () {}; 87 return hello; 88 });
js模組規範