Requirejs定義模組

來源:互聯網
上載者:User

標籤:requirejs   按需載入   

模組可以很好的定義範圍來避免全域名稱空間汙染,它可以顯示的定義出函數間的依賴關係,而不需要引用全域變數。


RequireJS可以載入多個不同的模組,雖然載入的順序不一樣,但是能保證依賴的順序是正確的。


1.  當模組中只有索引值對時,可通過如下方式定義。

define({    name : "beautiful",    color: "yellow",    size: "3M"});


2. 當模組中沒有依賴,只有函數時,模組的格式如下

define(function() {return {                   name : "beautiful",    color: "yellow",    size: "3M"    }});


3. 當模組中有依賴函數時,先定義出依賴函數的路徑,依賴的函數的別名。

define(["./cart", "./inventory"], function(cart, inventory) {        return {                        name : "beautiful",    color: "yellow",    size: "3M"    addToCart: function() {        inventory.decrement(this);        cart.add(this);    }        }    });


4. 將模組定義為函數
define(["my/cart", "my/inventory"], function(cart, inventory) {            return function(title) {                    return title ? (window.title = title) :                   inventory.storeName + ‘ ‘ + cart.name;        }    });


通過上面的例子也許你已經注意到了,模組中的註冊的函數或對象都是在return中返回的。如果你自訂了一些函數應該模組通過return返回,否則模組是無法找到你定義的函數的。




本文出自 “這個人的IT世界” 部落格,請務必保留此出處http://favccxx.blog.51cto.com/2890523/1930268

Requirejs定義模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.