
- RequireJS 教程
- RequireJS - 主頁
- RequireJS - 概述
- RequireJS - 環境設定
- RequireJS - 配置
- RequireJS - AMD 模組
- RequireJS - 定義函式
- RequireJS - 最佳化器
- RequireJS - jQuery
- RequireJS - NodeJS
- RequireJS - Dojo
- RequireJS - CommonJS
- RequireJS - 外掛
- RequireJS 有用資源
- RequireJS - 快速指南
- RequireJS - 有用資源
- RequireJS - 討論
RequireJS - 定義函式
define()函式可用於載入模組(模組可以是物件、函式、類或載入模組後執行的程式碼)。你可以在同一頁面上載入同一模組的不同版本。即使按不同順序載入,也可以按相同順序分析不同的版本。
語法
define(['module1', 'module2'], function (module1, module2) { //define the module value by returning a value return function () {}; });
在定義模組時可以傳遞一列模組名稱,並且在執行模組之前,RequireJS 可用於檢索這些模組。這些模組可以作為定義函式的引數進行傳遞。
示例
以下示例顯示了載入模組時define() 函式的用法。使用index.html名稱建立 html 檔案,並在其中放置以下程式碼 −
<!DOCTYPE html> <html> <head> <title>Define() Function</title> <script data-main = "main" src = "require.js"></script> </head> <body> <h2>RequireJS Define() Function Example</h2> </body> </html>
建立一個main.js名稱的js檔案,並新增以下程式碼 −
define(function (require) { var myteam = require("./team"); var mylogger = require("./player"); alert("Player Name : " + myteam.player); mylogger.myfunc(); });
現在,再建立兩個team.js和player.js名稱的js檔案,並分別放置以下程式碼 −
team.js
define({ player: "Sachin Tendulkar", team : "India" });
player.js
define(function (require) { var myteam = require("./team"); return { myfunc: function () { document.write("Name: " + myteam.player + ", Country: " + myteam.team); } }; });
輸出
在瀏覽器中開啟 HTML 檔案;你會看到一個輸出,如下面的截圖所示 −

單擊“OK”按鈕,你將獲得另一個來自模組的輸出 −

廣告