jQuery 插件開發分為類別級(靜態方法)與實例級(原型方法)兩種模式。理解 `$.extend()`、`$.fn.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);
掛載在 `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);
遵循此模式開發的插件,具備一致性 API、良好封裝、易測試、易維護,符合社群慣例。