一、原型模式結構
1 // 定義一個jQuery構造函數 2 var jQuery = function() { 3 4 }; 5 6 // 擴展jQuery原型 7 jQuery.prototype = { 8 9 };
上面是一個原型模式結構,一個jQuery構造函數和jQuery實例化對象的的原型對象,我們一般是這樣使用的:
1 var jq = new jQuery(); //變量jq通過new關鍵字實例化jQuery構造函數后就可以使用原型對象中的方法,但是jQuery並不是這么使用的
二、返回選擇器實例
1 var jQuery = function() { 2 3 // 返回選擇器實例 4 return new jQuery.prototype.init(); 5 }; 6 jQuery.prototype = { 7 8 // 選擇器構造函數 9 init: function() { 10 11 } 12 };
雖然jQuery不是通過new關鍵字實例化對象,但是執行jQuery函數仍然得到的是一個通過new關鍵字實例化init選擇器的對象,如:
1 var navCollections = jQuery('.nav'); //變量navCollections保存的是class名為nav的DOM對象集合.
三、訪問原型方法
1 var jQuery = function() { 2 3 // 返回選擇器實例 4 return new jQuery.prototype.init(); 5 }; 6 jQuery.prototype = { 7 8 // 選擇器構造函數 9 init: function() { 10 11 }, 12 13 // 原型方法 14 toArray: function() { 15 16 }, 17 get: function() { 18 19 } 20 }; 21 22 // 共享原型 23 jQuery.prototype.init.prototype = jQuery.prototype;
我們一般習慣稱jQuery函數中返回的選擇器實例對象為jQuery對象,如我們可以這樣使用:
1 jQuery('.nav').toArray(); // 將結果集轉換為數組
為什么可以使用toArray方法呢? 即如何讓jQuery對象訪問jQuery.prototype對象中的方法?只需將實例化選擇器對象的原型對象共享jQuery.prototype對象,上面體現代碼為:
1 jQuery.prototype.init.prototype = jQuery.prototype; // 共享原型
四、自執行匿名函數
1 (function(window, undefined) { 2 3 var jQuery = function() { 4 5 // 返回選擇器實例 6 return new jQuery.prototype.init(); 7 }; 8 jQuery.prototype = { 9 10 // 選擇器構造函數 11 init: function() { 12 13 }, 14 15 //原型方法 16 toArray: function() { 17 18 }, 19 get: function() { 20 21 } 22 }; 23 jQuery.prototype.init.prototype = jQuery.prototype; 24 25 // 局部變量和函數在匿名函數執行完后撤銷 26 var a, b, c; 27 function fn() { 28 29 } 30 31 // 使jQuery成為全局變量 32 window.jQuery = window.$ = jQuery; 33 34 })(window);
自執行匿名函數中聲明的局部變量和函數在匿名函數執行完畢后撤銷,釋放內存,對外只保留jQuery全局變量接口。
轉載請注明轉自博客園淺析jQuery基礎框架