| 方法 | 掛載目標 | 用途 | 調用方式 |
|---|---|---|---|
jQuery.extend() | jQuery 构造函數 (靜態方法) | 工具函數、配置選項合並、命名空間擴展 | $.fn.myUtil() |
jQuery.fn.extend() | jQuery.prototype (實例方法) | 鏈式調用插件、DOM 操作方法 | $('#id').myPlugin() |
核心事實:jQuery.fn === jQuery.prototype,兩者共用同一份 extend 實現邏輯,只是 target 默認值不同。
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {}, // 默認目標對象
i = 1, // 源對象起始索引
length = arguments.length,
deep = false; // 是否深度合並
// 處理深度合並參數: $.extend(true, target, obj1, obj2)
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
i = 2;
}
// 處理單參數: $.extend({method:...}) → target = this (jQuery 或 jQuery.fn)
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) ||
(copyIsArray = jQuery.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// 遞歸調用 extend 合並
target[name] = jQuery.extend(deep, clone, copy);
// 淺拷貝: 直接賦值 (undefined 不覆蓋)
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
};
var defaults = { timeout: 3000, retry: 3, cache: true };
var options = { timeout: 5000, debug: true };
var config = $.extend({}, defaults, options); // 不修改 defaults
// { timeout: 5000, retry: 3, cache: true, debug: true }
$.extend({
formatMoney: function(val) {
return '¥' + val.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
},
getUrlParam: function(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(location.search);
return match ? decodeURIComponent(match[1]) : null;
}
});
// 調用
$.formatMoney(1234.5); // "¥1,234.50"
$.getUrlParam('id');
$.fn.extend({
// 禁用/啟用表單
disable: function() {
return this.each(function() {
this.disabled = true;
});
},
enable: function() {
return this.each(function() {
this.disabled = false;
});
},
// 彈窗提示插件
toast: function(message, duration) {
return this.each(function() {
var $el = $(this);
var $toast = $('' + message + '')
.appendTo('body')
.fadeIn();
setTimeout(function() {
$toast.fadeOut(function() { $(this).remove(); });
}, duration || 2000);
});
}
});
// 使用
$('button').disable();
$('#msg').toast('操作成功!');
var defaults = {
ajax: { timeout: 3000, headers: { 'X-API': 'v1' } },
ui: { theme: 'dark', animations: true }
};
var userConfig = {
ajax: { timeout: 5000 }, // 僅覆蓋 timeout,保留 headers
ui: { theme: 'light' }
};
var config = $.extend(true, {}, defaults, userConfig);
// 結果:
/*
{
ajax: { timeout: 5000, headers: { 'X-API': 'v1' } },
ui: { theme: 'light', animations: true }
}
*/
var a = { x: 1 };
var b = { y: 2 };
// ❌ 修改了 a
$.extend(a, b);
console.log(a); // { x: 1, y: 2 }
// ✅ 不修改任何原對象
var c = $.extend({}, a, b);
console.log(a); // { x: 1 }
console.log(c); // { x: 1, y: 2 }
(function($) {
// 默認配置
var defaults = {
color: 'red',
duration: 300,
onComplete: null
};
// 構造函數
function Highlight(element, options) {
this.$el = $(element);
this.opts = $.extend({}, defaults, options);
this.init();
}
// 原型方法
Highlight.prototype = {
init: function() {
this.$el.css('background-color', this.opts.color);
},
flash: function() {
this.$el.fadeOut(this.opts.duration).fadeIn(this.opts.duration,
this.opts.onComplete);
}
};
// 註冊為 jQuery 插件
$.fn.highlight = function(options) {
return this.each(function() {
// 防止重複初始化
if (!$.data(this, 'plugin_highlight')) {
$.data(this, 'plugin_highlight', new Highlight(this, options));
}
});
};
// 暴露構造函數供高級用法
$.fn.highlight.Constructor = Highlight;
})(jQuery);
// 使用
$('.important').highlight({ color: 'yellow', duration: 500 });
$.extend(true, [1,2], [3,4]) 結果 {0:3, 1:4, length:2} (數組視為對象),需用 concat$.extend({a:1}, {a:undefined}) 保留 a:1target === copy 防護,但深層循環仍可能棧溢出this 是 jQuery 對象,回調中需 .each() 遍歷掌握 extend 機制是編寫高質量 jQuery 插件、理解 jQuery 核心架構的關鍵。