讀 jQuery 源碼時,你會反覆遇到同一個函數:extend。它既是 jQuery 的擴展入口,也是 jQuery 自身各模組互相「掛件」的方式。可以說,理解了 extend,就理解了 jQuery 為什麼能長成一個龐大 yet 靈活的工具庫。
jQuery.fn.extend 提供的是一套「批量拷貝成員」的能力:你可以傳入一個或多個參考物件,把它們的屬性逐一搬到目標物件上。如果不告訴它目標是誰,它就默認把成員掛到自己身上——這正是絕大多數 jQuery 外掛的寫法來源。
而 jQuery.extend 與 jQuery.fn.extend 其實是同一個函數。前者用來給 jQuery 這個「類」增加靜態方法,後者用來給 jQuery.fn(也就是 jQuery.prototype)增加例項方法,從而在所有選中的元素上都能調用。
假設要為 jQuery.fn 補上 removeData,只需要寫一個物件傳進去即可:
jQuery.fn.extend({
removeData: function (key) {
return this.each(function () {
jQuery.removeData(this, key);
});
}
});
extend 的實作邏輯並不複雜,下面幾乎保留了原貌:
/// <reference path="jQuery-core.js" />
jQuery.extend = jQuery.fn.extend = function () {
// 取出目標物件
var target = arguments[0] || {}, i = 1, length = arguments.length,
deep = false, options, name, src, copy;
// 第一個參數是 boolean,表示深拷貝;此時目標物件順移到第二位
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
i = 2; // 跳過 boolean 與目標物件
}
// 目標既不是物件也不是函數,則重置為空物件
if (typeof target !== "object" && !jQuery.isFunction(target)) {
target = {};
}
// 只傳了一個參數,說明是在擴展自己
if (length === i) {
target = this;
--i;
}
// 遍歷所有參考物件
for (; i < length; i++) {
if ((options = arguments[i]) != null) {
for (name in options) {
src = target[name];
copy = options[name];
// 避免自己拷貝自己造成死迴圈
if (target === copy) {
continue;
}
// 深拷貝時,遇到純物件或陣列則遞迴處理
if (deep && copy && (jQuery.isPlainObject(copy) || jQuery.isArray(copy))) {
var clone = src && (jQuery.isPlainObject(src) || jQuery.isArray(src))
? src
: jQuery.isArray(copy) ? [] : {};
target[name] = jQuery.extend(deep, clone, copy);
}
// 淺拷貝:不搬 undefined
else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
};
jQuery.extend(true, {}, a, b) 會遞迴合併,適合處理巢狀設定物件。target = this 實現,這也是 jQuery.extend({...}) 能直接為 jQuery 添加靜態方法的原因。target === copy 時跳過,避免物件自我參照導致遞迴失控。把這些規則記牢,之後讀 jQuery 其他模組(ajax 的參數合併、外掛的 options 覆寫)都會輕鬆很多。