在我最初開始寫 JavaScript 函數時,通常是這樣的:
function fun1() { // some code here}function fun2() { // some other code here}...函數全寫在全局環境中,項目很小時,通常不會有什么沖突問題。
但代碼多了后,漸漸就發現,函數名稱(英文詞匯)有點不夠用了。于是引入命名空間的概念,開始模塊化代碼。
命名空間下的函數
在命名空間下,我的代碼這樣寫:
var com = com || {};com.zfanw = com.zfanw || {};com.zfanw.module1 = (function() { // some code here return { func1: func1, ... };}());com.zfanw.module2 = (function() { // some other code here return { func1: func1, ... };}());...本著要面向對象的原則,執行函數通常我要這么寫的:
com.zfanw.module1.func1.apply({},['arg1',arg2]);...當然,為了少打些字符,我還會在閉包中導入1公共 API 接口:m.survivalescaperooms.com
(function($, mod1) { // some code here mod1.func1.apply({},['arg1',arg2]);}(jQuery, com.zfanw.module1));... 至此,代碼沖突的可能性已經很小,但代碼依賴的問題,多腳本文件管理、阻塞的問題,漸漸浮出水面 – 命名空間的辦法開始捉急。
于是 Require.js2 出場。
Require.js
首先了解下 require.js 里模塊的概念3:
A module is different from a traditional script file in that it defines a well-scoped object that avoids polluting the global namespace. It can explicitly list its dependencies and get a handle on those dependencies without needing to refer to global objects, but instead receive the dependencies as arguments to the function that defines the module.
簡單地說,有兩點,一、模塊作用域自成一體,不污染全局空間;二、模塊指明依賴關系,并且依賴是通過參數傳遞的形式導入的,無需通過全局對象引用 – 依賴同樣不污染全局空間。
定義模塊
與上面的老長的命名空間方式不同,require.js 用全局方法 define 來定義模塊,形式如下:
define(id?, dependencies?, factory); // ? 表示可選項
我且把模塊分兩種。
無依賴的模塊
假如一個模塊并不依賴其他模塊,那么定義起來是很簡單的,比如模塊 hello 放在 hello.js 文件中:
define(function() { // some code here return { // some public api };}); 有依賴的模塊
有依賴的模塊要稍稍復雜點,define 時,我們需要羅列出模塊的依賴情況:
define(['jquery'], function($) { // 比如這個模塊,代碼的執行依賴 jQuery,require.js 會先加載 jquery 模塊代碼,并加以執行,然后將依賴模塊 以 $ 的參數形式傳入回調函數中,回調函數將執行結果注冊為模塊 // maybe some code here return { // some public api };});
|
新聞熱點
疑難解答
圖片精選