萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery.fn 與 jQuery.extend 區別詳解:靜態方法 vs 實例方法擴充

一句話總結

  • 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(原型物件)。

常見誤區

  1. 以為 $.fn.extend 只能寫插件——其實任何掛在原型上的函數都是實例方法。
  2. 在插件內部用 $.extend 合併選項:var opts = $.extend({}, defaults, options); 這是靜態方法用法,**不是**在擴充 jQuery。
  3. 忘記回傳 this 導致鏈式中斷:實例方法應 return this.each(...) 或 return this。

現代替代:ES6 Class / 模組化

// 工具函數模組
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 / 函數式工具庫,享受樹搖、型別檢查與更好的封裝性。

copyright © 萬盛學電腦網 all rights reserved