一、原型模式結(jié)構(gòu)
代碼如下:
// 定義一個jQuery構(gòu)造函數(shù)
var jQuery = function() {
};
// 擴(kuò)展jQuery原型
jQuery.prototype = {
};
上面是一個原型模式結(jié)構(gòu),一個jQuery構(gòu)造函數(shù)和jQuery實例化對象的的原型對象,我們一般是這樣使用的:
代碼如下:
var jq = new jQuery(); //變量jq通過new關(guān)鍵字實例化jQuery構(gòu)造函數(shù)后就可以使用原型對象中的方法,但是jQuery并不是這么使用的
二、返回選擇器實例
代碼如下:
var jQuery = function() {
// 返回選擇器實例
return new jQuery.prototype.init();
};
jQuery.prototype = {
// 選擇器構(gòu)造函數(shù)
init: function() {
}
};
雖然jQuery不是通過new關(guān)鍵字實例化對象,但是執(zhí)行jQuery函數(shù)仍然得到的是一個通過new關(guān)鍵字實例化init選擇器的對象,如:
var navCollections = jQuery('.nav'); //變量navCollections保存的是class名為nav的DOM對象集合.
三、訪問原型方法
代碼如下:
var jQuery = function() {
// 返回選擇器實例
return new jQuery.prototype.init();
};
jQuery.prototype = {
// 選擇器構(gòu)造函數(shù)
init: function() {
},
// 原型方法
toArray: function() {
},
get: function() {
}
};
// 共享原型
jQuery.prototype.init.prototype = jQuery.prototype;
我們一般習(xí)慣稱jQuery函數(shù)中返回的選擇器實例對象為jQuery對象,如我們可以這樣使用:
代碼如下:
jQuery.('.nav').toArray(); // 將結(jié)果集轉(zhuǎn)換為數(shù)組
為什么可以使用toArray方法呢? 即如何讓jQuery對象訪問jQuery.prototype對象中的方法?只需將實例化選擇器對象的原型對象共享jQuery.prototype對象,上面體現(xiàn)代碼為:
代碼如下:
jQuery.prototype.init.prototype = jQuery.prototype; // 共享原型
四、自執(zhí)行匿名函數(shù)
代碼如下:
(function(window, undefined) {
var jQuery = function() {
// 返回選擇器實例
return new jQuery.prototype.init();
};
jQuery.prototype = {
// 選擇器構(gòu)造函數(shù)
init: function() {
},
//原型方法
toArray: function() {
},
get: function() {
}
};
jQuery.prototype.init.prototype = jQuery.prototype;
// 局部變量和函數(shù)在匿名函數(shù)執(zhí)行完后撤銷
var a, b, c;
function fn() {
}
// 使jQuery成為全局變量
window.jQuery = window.$ = jQuery;
})(window);
自執(zhí)行匿名函數(shù)中聲明的局部變量和函數(shù)在匿名函數(shù)執(zhí)行完畢后撤銷,釋放內(nèi)存,對外只保留jQuery全局變量接口。
來源: http://www.cnblogs.com/yangjunhua/archive/2012/12/27/2835989.html
新聞熱點
疑難解答
圖片精選