Asynchronous Module Definition AMD

suggest change

AMD is a module definition system that attempts to address some of the common issues with other systems like CommonJS and anonymous closures.

AMD addresses these issues by:

The key thing here is that a module can have a dependency and not hold everything up while waiting for it to load, without the developer having to write complicated code.

AMD loaders such as RequireJS provide define. It is not a built-in language function. Here’s an example:

// Define a module "myModule" with two dependencies, jQuery and Lodash
define("myModule", ["jquery", "lodash"], function($, _) {
    // This publicly accessible object is our module
    // Here we use an object, but it can be of any type
    var myModule = {};

    var privateVar = "Nothing outside of this module can see me";

    var privateFn = function(param) {
        return "Here's what you said: " + param;
    };

    myModule.version = 1;

    myModule.moduleMethod = function() {
        // Globals are still visible, but the injected dependencies are safer.
        // windowTitle must already exist; otherwise this throws ReferenceError.
        return privateFn(windowTitle);
    };

    return myModule;
});

Modules can also skip the name and be anonymous. When that’s done, they’re usually loaded by file name.

define(["jquery", "lodash"], function($, _) { /* factory */ });

They can also skip dependencies:

define(function() { /* factory */ });

Some AMD loaders support defining modules as plain objects:

define("myModule", { version: 1, value: "sample string" });

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents