jQuery.extend 是插件開發與設定合併的基石。它同時是 jQuery.fn.extend 的來源——差別只在於「只傳一個參數時,要擴充 jQuery 本身還是 jQuery 的原型」。以下是原始碼的逐段拆解。
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
第一個參數可以是 boolean。傳 true 就是深拷貝(deep copy),此時 target 順延到第二個參數,迴圈起點改為 2。這也是為什麼 $.extend(true, {}, a, b) 這種寫法能成立。
只傳一個參數時擴充自己。length === i 代表除了 target 之外沒有其他來源物件,於是 target 被改成 this,i 退一格,把唯一傳入的物件合併進 jQuery(或 jQuery.fn)。這正是插件開發時 $.extend({ myPlugin: function(){} }) 的運作原理。
target === copy 的防護。若來源物件指向自己,遞迴會無限循環,因此直接 continue 跳過。
深拷貝時一定要 clone。遇到 plain object 或 array 時,先依來源型別準備一個空殼([] 或 {}),再遞迴合併進去。註解寫得很明白:Never move original objects, clone them——否則改動結果會連帶污染原始設定。
undefined 不會被帶入。最後一個 else if 過濾掉 undefined,讓「用預設值 + 使用者設定」的合併模式不會被空值破壞。注意 null 是會被複製的,這點與 undefined 不同。
最常見的用法是為插件提供預設選項:
$.fn.tooltip = function(options){
var settings = $.extend({}, $.fn.tooltip.defaults, options);
// ...
};
$.fn.tooltip.defaults = { position: "top", duration: 300 };
傳入 {} 作為第一個參數是為了不污染 defaults 本身;若省掉它,使用者傳入的選項會直接寫進預設值,導致同一頁面其他實例也跟著改變——這是 extend 最經典的誤用。