一、原型模式結構
複製代碼 代碼如下:
// 定義一個jQuery建構函式
var jQuery = function() {
};
// 擴充jQuery原型
jQuery.prototype = {
};
上面是一個原型模式結構,一個jQuery建構函式和jQuery執行個體化對象的的原型對象,我們一般是這樣使用的:
複製代碼 代碼如下:
var jq = new jQuery(); //變數jq通過new關鍵字執行個體化jQuery建構函式後就可以使用原型對象中的方法,但是jQuery並不是這麼使用的
二、返回選取器執行個體
複製代碼 代碼如下:
var jQuery = function() {
// 返回選取器執行個體
return new jQuery.prototype.init();
};
jQuery.prototype = {
// 選取器建構函式
init: function() {
}
};
雖然jQuery不是通過new關鍵字執行個體化對象,但是執行jQuery函數仍然得到的是一個通過new關鍵字執行個體化init選取器的對象,如:
var navCollections = jQuery('.nav'); //變數navCollections儲存的是class名為nav的DOM對象集合.
三、訪問原型方法
複製代碼 代碼如下:
var jQuery = function() {
// 返回選取器執行個體
return new jQuery.prototype.init();
};
jQuery.prototype = {
// 選取器建構函式
init: function() {
},
// 原型方法
toArray: function() {
},
get: function() {
}
};
// 共用原型
jQuery.prototype.init.prototype = jQuery.prototype;
我們一般習慣稱jQuery函數中返回的選取器執行個體對象為jQuery對象,如我們可以這樣使用:
複製代碼 代碼如下:
jQuery.('.nav').toArray(); // 將結果集轉換為數組
為什麼可以使用toArray方法呢? 即如何讓jQuery對象訪問jQuery.prototype對象中的方法?只需將執行個體化選取器對象的原型對象共用jQuery.prototype對象,上面體現代碼為:
複製代碼 代碼如下:
jQuery.prototype.init.prototype = jQuery.prototype; // 共用原型
四、自執行匿名函數
複製代碼 代碼如下:
(function(window, undefined) {
var jQuery = function() {
// 返回選取器執行個體
return new jQuery.prototype.init();
};
jQuery.prototype = {
// 選取器建構函式
init: function() {
},
//原型方法
toArray: function() {
},
get: function() {
}
};
jQuery.prototype.init.prototype = jQuery.prototype;
// 局部變數和函數在匿名函數執行完後撤銷
var a, b, c;
function fn() {
}
// 使jQuery成為全域變數
window.jQuery = window.$ = jQuery;
})(window);
自執行匿名函數中聲明的局部變數和函數在匿名函數執行完畢後撤銷,釋放記憶體,對外只保留jQuery全域變數介面。
來源: http://www.cnblogs.com/yangjunhua/archive/2012/12/27/2835989.html