萬盛學電腦網

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

jQuery 插件開發精要:全局函數、對象方法、鏈式調用與參數默認值

jQuery 插件架構三層次

層次掛載位置調用方式適用場景
全局函數jQuery.fn / jQuery$.myFunc()工具函數、命名空間、無 DOM 依賴邏輯
對象方法jQuery.fn (即 jQuery.prototype)$("selector").myMethod()操作 DOM 元素、鏈式調用、隱式迭代
選擇器擴展jQuery.expr[":"]$("div:myCustom")自定義選擇器邏輯

一、全局函數:擴展 jQuery 命名空間

1.1 單個函數(不推薦:汙染命名空間)

jQuery.myUtil = function() { alert("工具函數"); };
$.myUtil(); // 調用

1.2 多個函數(同樣汙染)

jQuery.utilA = function() { ... };
jQuery.utilB = function() { ... };
$.utilA(); $.utilB();

1.3 命名空間模式(推薦:避免衝突)

jQuery.myPlugin = {
    version: "1.0.0",
    author: "Team",
    
    // 工具函數
    formatDate: function(date, fmt) { ... },
    
    // 配置管理
    config: { debug: false },
    
    // 內部方法(慣例下劃線前綴)
    _internalHelper: function() { ... },
    
    // 初始化入口
    init: function(options) {
        this.config = $.extend(this.config, options);
    }
};

// 使用
$.myPlugin.init({ debug: true });
$.myPlugin.formatDate(new Date(), "yyyy-MM-dd");

二、對象方法:jQuery.fn 的藝術

2.1 基礎模板

jQuery.fn.myPlugin = function(options) {
    // this 指向 jQuery 對象(包含 0~N 個 DOM 元素)
    return this.each(function() {
        // this 指向單個 DOM 元素
        var $el = $(this);
        // 插件邏輯...
    });
};

2.2 核心原則:隱式迭代

永遠在方法內部使用 this.each() 遍歷匹配元素集合,確保插件行為與 jQuery 內置方法一致(如 css(), hide())。

反面教材:缺少 each 導致錯誤

// ❌ 錯誤:直接操作 this(jQuery 對象),僅影響第一個元素或行為異常
jQuery.fn.badSwap = function(class1, class2) {
    if (this.hasClass(class1)) this.removeClass(class1).addClass(class2);
    // 多個元素時,this.hasClass 只檢查第一個,addClass 應用於所有,邏輯錯亂
};

// ✅ 正確:隱式迭代
jQuery.fn.goodSwap = function(class1, class2) {
    return this.each(function() {
        var $el = $(this);
        if ($el.hasClass(class1)) $el.removeClass(class1).addClass(class2);
        else if ($el.hasClass(class2)) $el.removeClass(class2).addClass(class1);
    });
};

2.3 鏈式調用:返回 this

jQuery.fn.chainable = function() {
    return this.each(function() {
        // 處理邏輯
    });
};

// 支持鏈式:$("div").chainable().css("color", "red").fadeIn();

三、參數處理:defaults + extend 模式

3.1 基礎參數映射

jQuery.fn.shadow = function(opts) {
    return this.each(function() {
        var $el = $(this);
        for (var i = 0; i < opts.slices; i++) {
            $el.clone().css({
                position: "absolute",
                left: $el.offset().left + i,
                top: $el.offset().top + i,
                zIndex: opts.zIndex,
                opacity: opts.opacity
            }).appendTo("body");
        }
    });
};

// 調用:$("h1").shadow({ slices: 5, opacity: 0.25, zIndex: -1 });

3.2 默認參數合併:$.extend 核心模式

jQuery.fn.shadow = function(options) {
    // 1. 定義默認值
    var defaults = {
        slices: 5,
        opacity: 0.1,
        zIndex: -1
    };
    
    // 2. 合併:用戶選項覆蓋默認值
    // 注意:$.extend(target, source1, source2...) 修改並返回目標對象
    var opts = $.extend({}, defaults, options); // {} 為空目標,不汙染 defaults
    
    return this.each(function() {
        // 使用 opts.slices, opts.opacity...
    });
};

// 調用:$("h1").shadow({ opacity: 0.05 }); // 只覆蓋 opacity,其余用默認值

3.3 回調函數參數

jQuery.fn.shadow = function(options) {
    var defaults = {
        slices: 5,
        opacity: 0.1,
        zIndex: -1,
        // 回調函數:計算每層偏移
        sliceOffset: function(i) { return { x: i, y: i }; }
    };
    var opts = $.extend({}, defaults, options);
    
    return this.each(function() {
        var $el = $(this);
        for (var i = 0; i < opts.slices; i++) {
            var offset = opts.sliceOffset(i); // 調用回調
            $el.clone().css({
                left: $el.offset().left + offset.x,
                top: $el.offset().top + offset.y,
                zIndex: opts.zIndex,
                opacity: opts.opacity
            }).appendTo("body");
        }
    });
};

// 自定義偏移邏輯
$("h1").shadow({
    sliceOffset: function(i) { return { x: -i, y: -2*i }; }
});

3.4 可定制的默認值:插件命名空間存儲

jQuery.fn.shadow = function(options) {
    // 默認值存儲在插件函數屬性上,允許全局修改
    var opts = $.extend({}, jQuery.fn.shadow.defaults, options);
    // ...
};

// 定義默認值(函數也是對象)
jQuery.fn.shadow.defaults = {
    slices: 5,
    opacity: 0.1,
    zIndex: -1,
    sliceOffset: function(i) { return { x: i, y: i }; }
};

// 全局修改默認值(影響後續所有調用)
$.fn.shadow.defaults.opacity = 0.2;
$.fn.shadow.defaults.slices = 3;

// 單次調用覆蓋
$("h1").shadow({ opacity: 0.05 });

四、完整插件模板(現代寫法)

(function($, window, document, undefined) {
    "use strict";
    
    var pluginName = "myPlugin";
    var defaults = {
        property: "value",
        onInit: null,
        onChange: null
    };

    function Plugin(element, options) {
        this.element = element;
        this.$element = $(element);
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    $.extend(Plugin.prototype, {
        init: function() {
            this.setup();
            this.bindEvents();
            if ($.isFunction(this.settings.onInit)) {
                this.settings.onInit.call(this.element);
            }
        },
        setup: function() { /* 初始化 DOM、變量 */ },
        bindEvents: function() { /* 綁定事件 */ },
        destroy: function() {
            this.unbindEvents();
            this.$element.removeData(pluginName);
        }
    });

    // 防止重複實例化
    $.fn[pluginName] = function(options) {
        var args = arguments;
        return this.each(function() {
            var $this = $(this);
            var instance = $this.data(pluginName);
            
            if (!instance) {
                // 新建實例
                instance = new Plugin(this, typeof options === "object" ? options : {});
                $this.data(pluginName, instance);
            } else if (typeof options === "string") {
                // 調用實例方法:$("div").myPlugin("methodName", arg1, arg2)
                if (typeof instance[options] === "function") {
                    instance[options].apply(this, Array.prototype.slice.call(args, 1));
                }
            }
        });
    };

    // 暴露默認值允許全局修改
    $.fn[pluginName].defaults = defaults;

})(jQuery, window, document);

五、最佳實踐清單

  1. IIFE 包裹: (function($){ ... })(jQuery); 避免全局汙染、支持無衝突模式
  2. 命名空間: 全局函數歸入 $.myPlugin,對象方法掛 $.fn.myPlugin
  3. 隱式迭代: return this.each(...)
  4. 鏈式調用: return this
  5. 參數合併: $.extend({}, defaults, options)
  6. 默認值外掛: $.fn.plugin.defaults = {...}
  7. 實例緩存: .data(pluginName, instance) 防重複初始化
  8. 方法調用: 字符串參數調用實例方法 $().plugin("method", args)
  9. 銷毀方法: 提供 destroy() 清理事件、數據、DOM
  10. 文檔化: JSDoc 註釋所有公開 API

總結

jQuery 插件開發的核心在於理解 jQuery.fn 原型機制、掌握 each 隱式迭代與 extend 參數合併模式。從簡單的全局工具函數到功能完整的狀態化插件,遵循「單一職責、鏈式調用、可配置、可銷毀」原則,能編寫出像官方方法一樣優雅、健壯的插件。現代項目雖多用 Vue/React 組件,但 jQuery 插件模式在存量項目維護、輕量級交互、無框架頁面中依然閃光。

copyright © 萬盛學電腦網 all rights reserved