jQuery的初始化與對象構建之淺析
更新時間:2011年04月12日 00:14:37 作者:
之前本人的工作和學習多以原生js 為主,對jQuery 一直都不是很了解,但jQuery 作為當今最優(yōu)秀的js 類庫之一,必須是要花時間好好學習下的,今天正好蛋疼,讀了里面一些代碼
小結一下:
1.整個類庫定義在一匿名函數(shù)中,杜絕了全局變量的產(chǎn)生;
2.將undefined 作為缺失的參數(shù)傳遞,防止了undefined 變量的污染;
3.可以看出$(...) 實際上返回的是jQuery.fn.init 對象的實例,隨后將該對象的prototype 指向了jQuery.prototype (語句jQuery.fn.init.prototype = jQuery.fn),因此產(chǎn)生的實例共享著jQuery.prototype 里的方法和屬性且實現(xiàn)了鏈式編程的操作;
4.最后通過window.jQuery = window.$ = jQuery 將jQuery 與$ 導出為全局變量。
(function(window, undefined) {
// Define a local copy of jQuery
var jQuery = (function() {
var jQuery = function(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context/*, rootjQuery*/);
};
// ...
jQuery.fn = jQuery.prototype = {
constructor : jQuery,
init : function(selector, context, rootjQuery) {
// ...
}
// ...
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
// ...
// Expose jQuery to the global object
return jQuery;
})();
// ...
window.jQuery = window.$ = jQuery;
})(window);
1.整個類庫定義在一匿名函數(shù)中,杜絕了全局變量的產(chǎn)生;
2.將undefined 作為缺失的參數(shù)傳遞,防止了undefined 變量的污染;
3.可以看出$(...) 實際上返回的是jQuery.fn.init 對象的實例,隨后將該對象的prototype 指向了jQuery.prototype (語句jQuery.fn.init.prototype = jQuery.fn),因此產(chǎn)生的實例共享著jQuery.prototype 里的方法和屬性且實現(xiàn)了鏈式編程的操作;
4.最后通過window.jQuery = window.$ = jQuery 將jQuery 與$ 導出為全局變量。
復制代碼 代碼如下:
(function(window, undefined) {
// Define a local copy of jQuery
var jQuery = (function() {
var jQuery = function(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context/*, rootjQuery*/);
};
// ...
jQuery.fn = jQuery.prototype = {
constructor : jQuery,
init : function(selector, context, rootjQuery) {
// ...
}
// ...
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
// ...
// Expose jQuery to the global object
return jQuery;
})();
// ...
window.jQuery = window.$ = jQuery;
})(window);
相關文章
jQuery幫助之篩選查找 children([expr])
取得一個包含匹配的元素集合中每一個元素的所有子元素的元素集合。2011-01-01jQuery 可以拖動的div實現(xiàn)代碼 腳本之家修正版
最近研究了一下jQuery,覺得真的是一個很不錯的js庫,其他的不說,關鍵是有翔實的文檔,這點是非常關鍵的。2009-06-06jquery實現(xiàn)點擊其他區(qū)域時隱藏下拉div和遮罩層的方法
這篇文章主要介紹了jquery實現(xiàn)點擊其他區(qū)域時隱藏下拉div和遮罩層的方法,涉及jQuery響應鼠標事件動態(tài)改變頁面元素樣式的功能,需要的朋友可以參考下2015-12-12使用jQuery實現(xiàn)的網(wǎng)頁版的個人簡歷(可換膚)
點擊姓名會顯示她的基本詳細信息,點擊切換皮膚,會更改皮膚和字體大小感興趣的朋友可以參考下本文如何使用jQuery實現(xiàn)的網(wǎng)頁版的個人簡歷2013-04-04