萬盛學電腦網

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

jQuery 插件開發兩大模式:類別級擴展 vs 實例級擴展,與 $.fn.extend 深度解析

jQuery 插件開發分為類別級(靜態方法)與實例級(原型方法)兩種模式。理解 `$.extend()`、`$.fn.extend()` 差異、命名空間管理、鏈式呼叫、預設選項合併、銷毀模式,是編寫專業級插件的基石。

模式一:類別級擴展 (`$.extend`)

掛載在 `jQuery`/`$` 命名空間下,不依賴 DOM 元素,類似靜態工具函式。

$.extend({
  // 命名空間避免衝突
  myUtils: {
    formatDate(date, fmt = 'YYYY-MM-DD') {
      const o = { 'M+': date.getMonth()+1, 'd+': date.getDate(), 'h+': date.getHours() };
      return fmt.replace(/(Y+|M+|d+|h+|m+|s+)/g, (m, k) => {
        const v = String(o[k]).padStart(m.length, '0');
        return m.length === 1 ? v : v.slice(-m.length);
      });
    },
    debounce(fn, delay) {
      let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); };
    }
  }
});

// 使用
$.myUtils.formatDate(new Date()); // "2024-12-19"
const debounced = $.myUtils.debounce(save, 300);

模式二:實例級擴展 (`$.fn.extend`)

掛載在 `jQuery.fn` (即 `jQuery.prototype`),所有 jQuery 物件實例繼承,支援鏈式呼叫。

$.fn.extend({
  // 單一插件入口,選項物件模式
  myPlugin: function(options) {
    const opts = $.extend({
      color: 'red',
      speed: 300,
      onComplete: $.noop
    }, options);

    return this.each(function() { // 支援多元素、鏈式
      const $el = $(this);
      // 防止重複初始化
      if ($el.data('myPlugin')) return;
      
      const instance = new MyPluginCore($el, opts);
      $el.data('myPlugin', instance); // 緩存實例供後續調用
    });
  }
});

// 核心邏輯分離 (便於測試、擴展)
class MyPluginCore {
  constructor($el, opts) { this.$el = $el; this.opts = opts; this.init(); }
  init() { this.$el.css('color', this.opts.color).fadeIn(this.opts.speed, this.opts.onComplete); }
  destroy() { this.$el.removeData('myPlugin').off('.myPlugin').removeAttr('style'); }
}

// 使用
$('.box').myPlugin({ color: 'blue', speed: 500 });
// 後續調用實例方法
$('.box').first().data('myPlugin').destroy();

專業插件模板 (含銷毀、預設值、事件、資料快取)

;(function($, window, document, undefined) {
  const pluginName = 'tooltipster';
  const defaults = { content: '', position: 'top', delay: 200 };

  function Plugin(element, options) {
    this.element = element; this.$el = $(element);
    this.settings = $.extend({}, defaults, options, this.$el.data());
    this._init();
  }

  $.extend(Plugin.prototype, {
    _init() { /* 建構 DOM、綁定事件 */ },
    show() { /* 顯示邏輯 */ },
    hide() { /* 隱藏邏輯 */ },
    destroy() {
      this.$el.off(`.${pluginName}`).removeData(pluginName);
      // 移除建立的 DOM
    }
  });

  // 真正的 jQuery 插件入口
  $.fn[pluginName] = function(options) {
    const args = Array.prototype.slice.call(arguments, 1);
    return this.each(function() {
      let instance = $.data(this, pluginName);
      if (!instance) {
        instance = new Plugin(this, typeof options === 'object' ? options : {});
        $.data(this, pluginName, instance);
      }
      if (typeof options === 'string' && instance[options]) {
        return instance[options].apply(instance, args); // 允許調用實例方法
      }
    });
  };
})(jQuery, window, document);

關鍵最佳實踐

  • IIFE 隔離作用域,避免全域汙染,傳入 `$`, `window`, `document`, `undefined` 保證引用正確。
  • 選項合併優先序:預設值 < HTML `data-*` 屬性 < 傳入選項物件。
  • 單一入口,字串調用方法:`$el.plugin('methodName', arg1, arg2)` 模式。
  • 資料快取用 `$.data(el, key)`,非 `.data(key)`(後者有快取同步問題)。
  • 支援銷毀:移除事件、資料、建立的 DOM、定時器,防記憶體洩漏。
  • TypeScript 宣告:擴充 `JQuery` 介面 `interface JQuery { tooltipster(options?: TooltipsterOptions): JQuery; }`。

遵循此模式開發的插件,具備一致性 API、良好封裝、易測試、易維護,符合社群慣例。

copyright © 萬盛學電腦網 all rights reserved