Javascript AMD模塊化規范


AMD是"Asynchronous Module Definition"的縮寫,意思是"異步模塊定義"。

模塊定義
define(id?, dependencies?, factory);

其中:

  • id: 模塊標識,可以省略。
  • dependencies: 所依賴的模塊,可以省略。
  • factory: 模塊的實現,或者一個JavaScript對象。


代碼示例1: 定義一個alpha模塊,依賴require,exports,beta模塊

define("alpha", ["require", "exports", "beta"], function (require, exports, beta) {
     exports.verb = function() {
         return beta.verb();
         //Or:
         return require("beta").verb();
     }
}); 

 

代碼示例2: 定義個匿名模塊,依賴alpha模塊

define(["alpha"], function (alpha) {
    return {
        verb: function(){
            return alpha.verb() + 2;
        }
    };
});

 

代碼示例3: 使用JSON定義一個沒有依賴的匿名模塊。

 define({
   add: function(x, y){
     return x + y;
   }
 });

 

代碼示例4:定義一個兼容Modules/Wrappings模塊化規范的匿名模塊。

Modules/Wrappings是CommonJS Modules的瀏覽器端解決方案。AMD規范兼容Modules/Wrappings。

define(function (require, exports, beta) {
    exports.verb = function() {
        return beta.verb();
        //Or:
        return require("beta").verb();
    }
});

 

模塊加載
require([module], callback)

AMD模塊化規范中使用全局或局部的require函數實現加載一個或多個模塊,所有模塊加載完成之后的回調函數。

其中:

  • [module]:是一個數組,里面的成員就是要加載的模塊;
  • callback:是模塊加載完成之后的回調函數。

代碼示例:加載一個math模塊,然后調用方法 math.add(2, 3);

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

相關鏈接:

https://github.com/seajs/seajs/issues/269
http://www.cnblogs.com/snandy/archive/2012/03/09/2386092.html
http://www.zhihu.com/question/20351507
http://www.ruanyifeng.com/blog/2012/10/asynchronous_module_definition.html
http://seajs.org/docs/#docs


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM