extend() 是 jQuery 的基礎函式之一,作用是「用一個物件的屬性擴展另一個物件」。它看似簡單,但深淺複製的差異會引發相當隱晦的 bug。本文從行為談到實作,最後拆解官方版本的細節考量。
<script type="text/javascript" src="jquery-1.5.2.js"></script>
<script>
obj1 = { a: 'a', b: 'b' };
obj2 = { x: { xxx: 'xxx', yyy: 'yyy' }, y: 'y' };
$.extend(true, obj1, obj2);
alert(obj1.x.xxx); // "xxx"
obj2.x.xxx = 'zzz';
alert(obj2.x.xxx); // "zzz"
alert(obj1.x.xxx); // "xxx",不受影響
</script>
第一個參數設為 true 代表深複製。obj1 原本沒有 x 屬性,擴展後不但有了,而且改動 obj2.x 不會連帶影響 obj1.x。
$ = {
extend: function(target, options) {
for (name in options) {
target[name] = options[name];
}
return target;
}
};
用同樣的測試:
$.extend(obj1, obj2); alert(obj1.x.xxx); // "xxx" obj2.x.xxx = 'zzz'; alert(obj1.x.xxx); // "zzz",被連帶改掉了
問題就在這裡:obj1.x 與 obj2.x 指向同一個物件。這種「共用參照」造成的錯誤往往很難察覺,因為程式在當下看起來完全正常。
$ = {
extend: function(deep, target, options) {
for (name in options) {
copy = options[name];
if (deep && copy instanceof Array) {
target[name] = $.extend(deep, [], copy);
} else if (deep && copy instanceof Object) {
target[name] = $.extend(deep, {}, copy);
} else {
target[name] = options[name];
}
}
return target;
}
};
分三種情況:屬性是陣列就初始化為空陣列再遞迴;屬性是物件就初始化為空物件再遞迴;其餘直接賦值。
但 instanceof Array 在舊版 IE 上有相容問題,跨 iframe 情境下也可能誤判,所以官方實作得再謹慎一些。
$ = function() {
var copyIsArray,
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty;
var class2type = {
'[object Boolean]' : 'boolean',
'[object Number]' : 'number',
'[object String]' : 'string',
'[object Function]': 'function',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object RegExp]' : 'regExp',
'[object Object]' : 'object'
};
var type = function(obj) {
return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";
};
var isWindow = function(obj) {
return obj && typeof obj === "object" && "setInterval" in obj;
};
var isArray = Array.isArray || function(obj) {
return type(obj) === "array";
};
var isPlainObject = function(obj) {
if (!obj || type(obj) !== "object" || obj.nodeType || isWindow(obj)) {
return false;
}
if (obj.constructor && !hasOwn.call(obj, "constructor")
&& !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
var key;
for (key in obj) { }
return key === undefined || hasOwn.call(obj, key);
};
var extend = function(deep, target, options) {
for (name in options) {
src = target[name];
copy = options[name];
if (target === copy) { continue; }
if (deep && copy
&& (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
target[name] = extend(deep, clone, copy);
} else if (copy !== undefined) {
target[name] = copy;
}
}
return target;
};
return { extend: extend };
}();
立即執行函式:$ = function(){...}() 等同於先定義 func 再呼叫並賦值。這樣做有兩個好處:用函式建立獨立作用域,不污染全域;只把 extend 匯出,內部實作全部隱藏。
if (target === copy) continue; — 避免把「自己」設為「自己的屬性」而導致無限遞迴。
type 與 isArray — 若瀏覽器有原生 Array.isArray 就用它,否則把物件轉成字串判斷是否為 [object Array]。用 toString.call() 而非 instanceof,是為了避開跨框架與跨 iframe 的判斷失準。
isPlainObject 的四道關卡 — 以下情況不深複製:物件為 undefined;轉字串後不是 [object Object];是 DOM 元素(有 nodeType);是 window(有 setInterval)。DOM 與 window 屬性太多,深拷貝的代價過高。
constructor 檢查 — 若物件有 constructor 卻不是自身屬性,代表它是從 prototype 繼承來的,這類物件也不深複製。
屬性是否全為自身 — 遍歷時會先走自身屬性,因此只要檢查最後一個 key 是否屬於自身即可。這段邏輯搭配下面的測試就能看出效果:
function O() { this.yyy = 'yyy'; }
function X() { this.xxx = 'xxx'; }
X.prototype = new O();
x = new X();
obj1 = { a: 'a', b: 'b' };
obj2 = { x: x };
$.extend(true, obj1, obj2);
obj2.x.yyy = 'zzz';
alert(obj1.x.yyy); // "zzz",這種情況不深複製
jQuery 的 extend 之所以寫得這麼複雜,是在三件事之間取平衡:瀏覽器相容性、執行效能、以及避免引入不可預期的錯誤。也難怪它被視為原始碼中最值得細讀的片段之一——它示範了「看似單純的複製」在真實世界裡有多少邊界要處理。