標籤:
原文地址:http://blog.csdn.net/xiaogou56a/article/details/21340213
define 用來定義模組
require 用來載入模組
1
因為定義一個模組,可能會依賴其他模組,當然最簡單的情況下是不依賴其他模組,這時就可以這樣寫:
[javascript] view plaincopy
- //Inside file my/shirt.js:
- define({
- color: "black",
- size: "unisize"
- });
官方解釋:If the module does not have any dependencies, and it is just a collection of name/value pairs, then just pass an object literal to define():
2
定義一個模組,也可能需要先做一些setup工作,假設它也不依賴其他模組,這時可以這樣寫:
[javascript] view plaincopy
- //my/shirt.js now does setup work
- //before returning its module definition.
- define(function () {
- //Do setup work here
-
- return {
- color: "black",
- size: "unisize"
- }
- });
官方解釋:If the module does not have dependencies, but needs to use a function to do some setup work, then define itself, pass a function to define():
3
定義一個模組,可能會很複雜,既依賴其它一些個模組,又需要一些setup工作,那麼這個時候可以這樣寫:
[javascript] view plaincopy
- //my/shirt.js now has some dependencies, a cart and inventory
- //module in the same directory as shirt.js
- define(["./cart", "./inventory"], function(cart, inventory) {
- //return an object to define the "my/shirt" module.
- return {
- color: "blue",
- size: "large",
- addToCart: function() {
- inventory.decrement(this);
- cart.add(this);
- }
- }
- }
- );
被依賴的模組會作為參數一次傳入到那個function中。
看官方解釋:If the module has dependencies, the first argument should be an array of dependency names, and the second argument should be a definition function. The function will be called to define the module once all dependencies have loaded. The function should return an object that defines the module. The dependencies will be passed to the definition function as function arguments, listed in the same order as the order in the dependency array:
4
Define a Module with a Name
[javascript] view plaincopy
- //Explicitly defines the "foo/title" module:
- define("foo/title",
- ["my/cart", "my/inventory"],
- function(cart, inventory) {
- //Define foo/title object in here.
- }
- );
相信你一看便理解了,不過它裡面的學問可以在沒事的時候去看看官方的文檔說明,也許很有意思的哦。
還有好多其他情況,但記住本質,define是用來定義模組的,require是用來載入模組的,整個庫的開發考慮的情況比較多,比如:為了相容以前的代碼,為了適應某些庫的使用,某些轉換工具的使用,元編程的應用,等等。只要我們抓住本質,理解意思,具體的格式參考官網,只要別人用了,就肯定是合法的,就肯定是有根源的,今天到此為止。
requireJS define require