jQuery.extend(obj) → 擴充 **jQuery 建構函數(靜態方法)**,呼叫:$.fnName()jQuery.fn.extend(obj) → 擴充 **jQuery.prototype(實例方法)**,呼叫:$(selector).fnName()// 靜態方法:工具函數、命名空間
$.extend({
add: (a, b) => a + b,
namespace: { version: '1.0' }
});
$.add(3, 4); // 7
$.namespace.version; // '1.0'
// 實例方法:DOM 操作、UI 行為(插件)
$.fn.extend({
disable: function() { return this.prop('disabled', true); },
enable: function() { return this.prop('disabled', false); }
});
$('button').disable(); // 鏈式調用,回傳 jQuery 物件
jQuery.fn === jQuery.prototype; // true
// $.fn.extend(obj) 等價於 Object.assign(jQuery.prototype, obj)
jQuery 內部將兩者指向同一函數:
jQuery.extend = jQuery.fn.extend = function() { /* 合併邏輯 */ };
差別在於 this 指向:
$.extend(...) 時 this === jQuery(建構函數)。$.fn.extend(...) 時 this === jQuery.fn(原型物件)。$.fn.extend 只能寫插件——其實任何掛在原型上的函數都是實例方法。$.extend 合併選項:var opts = $.extend({}, defaults, options); 這是靜態方法用法,**不是**在擴充 jQuery。this 導致鏈式中斷:實例方法應 return this.each(...) 或 return this。// 工具函數模組
export const add = (a, b) => a + b;
// 類別式插件(無依賴)
class Tooltip {
constructor(el, options) { this.el = el; this.opts = options; this.init(); }
init() { /* ... */ }
static attach(selector, options) {
document.querySelectorAll(selector).forEach(el => new Tooltip(el, options));
}
}
Tooltip.attach('.tooltip', { theme: 'dark' });
理解 $.extend(靜態)與 $.fn.extend(實例)的分工,是 jQuery 插件開發與原始碼閱讀的基礎。現代專案建議改用 ES Modules + Class / 函數式工具庫,享受樹搖、型別檢查與更好的封裝性。