| 類型 | 掛載位置 | 調用方式 | 典型場景 |
|---|---|---|---|
| 對象級插件 | $.fn | $(selector).pluginName() | DOM 元素增強(Tabs、Slider、表單驗證) |
| 類級/全局函數 | $ / jQuery | $.pluginName() | 工具函數($.ajax、$.each) |
| 選擇器擴展 | $.expr[":"] | $(":customSelector") | 自定義選擇器(:external、:containsEx) |
;(function($, window, document, undefined) {
"use strict";
// 1. 插件名與預設配置
const pluginName = "myPlugin";
const defaults = {
color: "red",
speed: 300,
onComplete: $.noop
};
// 2. 建構函數
function Plugin(element, options) {
this.element = element;
this.$element = $(element);
this.settings = $.extend({}, defaults, options);
this._name = pluginName;
this.init();
}
// 3. 原型方法
$.extend(Plugin.prototype, {
init() {
this.bindEvents();
this.render();
},
bindEvents() {
this.$element.on("click." + pluginName, () => this.handleClick());
},
render() {
this.$element.css("color", this.settings.color);
},
handleClick() {
this.$element.fadeOut(this.settings.speed, () => {
this.$element.fadeIn(this.settings.speed);
this.settings.onComplete.call(this.element);
});
},
destroy() {
this.$element.off("." + pluginName);
this.$element.removeData(pluginName);
}
});
// 4. 掛載到 $.fn,防止重複實例化
$.fn[pluginName] = function(options) {
const args = arguments;
return this.each(function() {
const $this = $(this);
let instance = $this.data(pluginName);
if (!instance) {
// 初始化
if (typeof options === "object" || !options) {
instance = new Plugin(this, options);
$this.data(pluginName, instance);
}
} else if (typeof options === "string") {
// 呼叫實例方法
if (options === "destroy") {
instance.destroy();
$this.removeData(pluginName);
} else if (typeof instance[options] === "function") {
instance[options].apply(instance, Array.prototype.slice.call(args, 1));
}
}
});
};
})(jQuery, window, document);
;(function($, window, document, undefined) { ... })(jQuery, window, document);
undefined 保證 ES3 環境下 undefined 未被篡改window → w)click.myPlugin、resize.myPlugin —— destroy() 時 off(".myPlugin") 一次清理所有,不影響其他綁定。
.data()實例掛載在元素 data 上,避免全局變量污染,支援多實例獨立狀態。
// 初始化
$("#elem").myPlugin({ color: "blue" });
// 呼叫實例方法
$("#elem").myPlugin("destroy");
$("#elem").myPlugin("handleClick"); // 無參方法
// 獲取實例(進階)
const instance = $("#elem").data("myPlugin");
instance.settings.speed = 500;
$.extend// 深度合併:$.extend(true, {}, defaults, options)
// 淺層合併(常用):$.extend({}, defaults, options)
// 多對象合併:$.extend({}, defaults, options1, options2)
;(function($) {
$.myUtil = {
formatDate(date, fmt) { /* ... */ },
debounce(fn, delay) { /* ... */ }
};
// 或直接掛函數
$.showMsg = function(msg) { alert(msg); };
})(jQuery);
// 使用
$.myUtil.formatDate(new Date(), "yyyy-MM-dd");
$.showMsg("Hello");
jquery.myPlugin.js / jquery.myPlugin.min.jsnoConflict 模式(使用 jQuery 而非 $)新專案建議直接編寫 原生 JS Class/ES Module,無需 jQuery 依賴:
// my-plugin.js
export class MyPlugin {
constructor(element, options) { /* ... */ }
init() { /* ... */ }
destroy() { /* ... */ }
}
// 使用
import { MyPlugin } from "./my-plugin.js";
new MyPlugin(document.querySelector("#elem"), { color: "blue" });