forked from wchaowu/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
117 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
<h3>异步模块定义</h3><br /> | ||
AMD是"Asynchronous Module Definition"的缩写,意思就是"异步模块定义"。它采用异步方式加载模块,模块的加载不影响它后面语句的运行。<br /> | ||
所有依赖这个模块的语句,都定义在一个回调函数中,等到加载完成之后,这个回调函数才会运行。<br /> | ||
<br /> | ||
AMD也采用require()语句加载模块,但是不同于CommonJS,它要求两个参数:<br /> | ||
<code> | ||
|
||
require([module], callback); | ||
</code> | ||
|
||
第一个参数[module],是一个数组,里面的成员就是要加载的模块;第二个参数callback,则是加载成功之后的回调函数。如果将前面的代码改写成AMD形式,就是下面这样:<<br /> | ||
<code> | ||
|
||
require(['math'], function (math) { | ||
|
||
math.add(2, 3); | ||
|
||
}); | ||
<code> | ||
<br /> | ||
math.add()与math模块加载不是同步的,浏览器不会发生假死。所以很显然,AMD比较适合浏览器环境。<br /> | ||
|
||
目前,主要有两个Javascript库实现了AMD规范:require.js和curl.js。本系列的第三部分,将通过介绍require.js,进一步讲解AMD的用法,以及如何将模块化编程投入实战。<br /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
<h3>CommonJS</h3> | ||
|
||
2009年,美国程序员Ryan Dahl创造了node.js项目,将javascript语言用于服务器端编程。<br /> | ||
|
||
这标志"Javascript模块化编程"正式诞生。因为老实说,在浏览器环境下,没有模块也不是特别大的问题,毕竟网页程序的复杂性有限;<br /> | ||
但是在服务器端,一定要有模块,与操作系统和其他应用程序互动,否则根本没法编程。<br /> | ||
<br /> | ||
node.js的模块系统,就是参照CommonJS规范实现的。在CommonJS中,有一个全局性方法require(),用于加载模块。假定有一个数学模块math.js,就可以像下面这样加载。<br /> | ||
<code> | ||
var math = require('math'); | ||
<code> | ||
然后,就可以调用模块提供的方法:<br /> | ||
|
||
<code> | ||
var math = require('math'); | ||
math.add(2,3); // 5 | ||
<code> | ||
因为这个系列主要针对浏览器编程,不涉及node.js,所以对CommonJS就不多做介绍了。我们在这里只要知道,require()用于加载模块就行了 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters