Skip to content
This repository was archived by the owner on Mar 22, 2019. It is now read-only.
e-cloud edited this page Mar 22, 2016 · 2 revisions

AMD (Asynchronous Module Definition) was the response to those who thought the CommonJS Module system was not ready for the browser because its nature was synchronous.

部分开发者认为,CommonJS模块系统的本质是同步的,因此其尚不适用于浏览器环境。AMD (异步模块定义)则是他们的回应。

AMD specifies a standard for modular JavaScript such that modules can load their dependencies asynchronously, solving the problems associated with synchronous loading.

AMD 定义了一套Javascript模块化的标准,使模块可以异步加载其依赖,以解决同步加载的相关问题。

Specification 规范

Modules are defined using the define function.

使用define函数来定义模块

define

The define function is how modules are defined with AMD. It is just a function that has this signature

这个define函数是关于如何基于AMD来定义模块。只是一个带有以下签名的函数:

define(id?: String, dependencies?: String[], factory: Function|Object);

id

Specifies the module name. It is optional.

用于指定模块名。可选。

dependencies

This argument specifies which module dependencies the module being defined has. It is an array containing module identifiers. It is optional, but if omitted, it defaults to ["require", "exports", "module"].

这个参数用于声明当前定义的模块依赖了哪些模块。 它是含有模块标识符的数组。 它是可选的。但如果被省略,默认为["require", "exports", "module"]。

factory

The last argument is the one who defines the module. It can be a function (which should be called once), or an object. If the factory is a function, the value returned will be the exported value for the module.

最后一个参数是真正用于定义模块。它可以是一个函数(应该只被调用一次),或一个对象。 如果factory是一个函数,其返回值将是该模块的输出值。

Examples 例子

Let's see some examples:

让我们来看看一些例子:

Named module 具名模块

Defines a module named myModule that requires jQuery.

定义一个名为myModule的模块。其依赖jQuery

define('myModule', ['jquery'], function($) {
	// $ is the export of the jquery module.
	$('body').text('hello world');
});
// and use it
require(['myModule'], function(myModule) {});

Note: In webpack a named module is only locally available. In Require.js a named module is globally available.

注:在Webpack中,一个具名模块仅本地可用,而在Require.js一个具名模块全局可用。

Anonymous module 匿名模块

Define a module without specifying its id.

定义一个模块,而无需指定其ID。

define(['jquery'], function($) {
	$('body').text('hello world');
});

Multiple dependencies 多个依赖

Define a module with multiple dependencies. Note that each dependency export will be passed to the factory function.

定义具有多个依赖的模块。需要注意的是每个依赖将被作为参数传递给工厂函数(译者注:即是依赖注入)。

define(['jquery', './math.js'], function($, math) {
	// $ and math are the exports of the jquery module.
	$('body').text('hello world');
});

Export value 输出值

Define a module that exports itself.

定义一个输出其自身的模块。

define(['jquery'], function($) {

	var HelloWorldize = function(selector){
		$(selector).text('hello world');
	};

	return HelloWorldize;
});

Using require to load dependencies 用require加载依赖

define(function(require) {
	var $ = require('jquery');
	$('body').text('hello world');
});
Clone this wiki locally