CommonJS 和 AMD 規範?

來源:互聯網
上載者:User

標籤:

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( );

        }

    });


    

    


CommonJS 和 AMD 規範?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.