jQuery 作為當今最優(yōu)秀的js 類庫之一,必須是要花時間好好學習下的,今天正好蛋疼,讀了里面一些代碼,小結一下:
整個類庫定義在一匿名函數中,杜絕了全局變量的產生;
將undefined 作為缺失的參數傳遞,防止了undefined 變量的污染;
可以看出$(...) 實際上返回的是jQuery.fn.init 對象的實例,隨后將該對象的prototype 指向了jQuery.prototype (語句jQuery.fn.init.prototype = jQuery.fn),因此產生的實例共享著jQuery.prototype 里的方法和屬性且實現了鏈式編程的操作;
最后通過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);