把 jQuery 的原始碼骨架抽出來看,會發現它的設計相當克制,幾個關鍵手法值得記下來。
1、整個類庫定義在一個匿名函式中,杜絕了全域變數的產生。
2、將 undefined 作為缺失的參數傳入,避免全域 undefined 被汙染時造成的判斷失效。
3、$(...) 實際上回傳的是 jQuery.fn.init 物件的實例;隨後透過 jQuery.fn.init.prototype = jQuery.fn 把 init 的原型指向 jQuery.prototype,因此產生的實例共享 jQuery.prototype 上的方法與屬性,鏈式呼叫(chaining)也因此得以實現。
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.fn(也就是 prototype 物件),再把 init 的原型指向它。如此一來,new jQuery.fn.init(...) 建構出來的物件,天生就帶有 jQuery.fn 上的全部方法,$("div").css() 這種鏈式寫法才成立。這也是 jQuery 能在「函式」與「物件」兩種身分之間自由切換的關鍵。