1.requirejs定義的模塊返回的是單例對象.定義模塊有下面幾種方式html
簡單的值對:若是一個模塊僅含值對,沒有任何依賴,則在define()中定義這些值對就行了api
//Inside file my/shirt.js: define({ color: "black", size: "unisize" });
函數式定義:若是一個模塊沒有任何依賴,但須要一個作setup(初始化工做之類)工做的函數,則在define()中定義該函數,並將其傳給define():數組
//my/shirt.js now does setup work //before returning its module definition. define(function () { //Do setup work here return { color: "black", size: "unisize" } });
存在依賴的函數式定義:若是模塊存在依賴:則第一個參數是依賴的名稱數組;第二個參數是函數,在模塊的全部依賴加載完畢後,該函數會被調用來定義該模塊,所以該模塊應該返回一個定義了本模塊的object。依賴關係會以參數的形式注入到該函數上,參數列表與依賴名稱列表一一對應。app
//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); } } } );
本示例建立了一個my/shirt模塊,它依賴於my/cart及my/inventory。磁盤上各文件分佈以下: ide
模塊函數以參數"cart"及"inventory"使用這兩個以"./cart"及"./inventory"名稱指定的模塊。在這兩個模塊加載完畢以前,模塊函數不會被調用。函數
嚴重不鼓勵模塊定義全局變量。遵循此處的定義模式,能夠使得同一模塊的不一樣版本並存於同一個頁面上(參見 高級用法 )。另外,函參的順序應與依賴順序保存一致。 requirejs
返回的object定義了"my/shirt"模塊。這種定義模式下,"my/shirt"不做爲一個全局變量而存在。 ui
將模塊定義爲一個函數:對模塊的返回值類型並無強制爲必定是個object,任何函數的返回值都是容許的。此處是一個返回了函數的模塊定義:this
//A module definition inside foo/title.js. It uses //my/cart and my/inventory modules from before, //but since foo/title.js is in a different directory than //the "my" modules, it uses the "my" in the module dependency //name to find them. The "my" part of the name can be mapped //to any directory, but by default, it is assumed to be a //sibling to the "foo" directory. define(["my/cart", "my/inventory"], function(cart, inventory) { //return a function to define "foo/title". //It gets or sets the window title. return function(title) { return title ? (window.title = title) : inventory.storeName + ' ' + cart.name; } } );