萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

jQuery extend() 與 fn.extend() 深度解析:插件開發核心機制

兩大擴展方法本質區別

方法掛載目標用途調用方式
jQuery.extend()jQuery 构造函數 (靜態方法)工具函數、配置選項合並、命名空間擴展$.fn.myUtil()
jQuery.fn.extend()jQuery.prototype (實例方法)鏈式調用插件、DOM 操作方法$('#id').myPlugin()

核心事實:jQuery.fn === jQuery.prototype,兩者共用同一份 extend 實現邏輯,只是 target 默認值不同。

源碼核心邏輯 (jQuery 1.7.1)


jQuery.extend = jQuery.fn.extend = function() {
    var options, name, src, copy, copyIsArray, clone,
        target = arguments[0] || {},  // 默認目標對象
        i = 1,                        // 源對象起始索引
        length = arguments.length,
        deep = false;                 // 是否深度合並
    
    // 處理深度合並參數: $.extend(true, target, obj1, obj2)
    if (typeof target === "boolean") {
        deep = target;
        target = arguments[1] || {};
        i = 2;
    }
    
    // 處理單參數: $.extend({method:...}) → target = this (jQuery 或 jQuery.fn)
    if (length === i) {
        target = this;
        --i;
    }
    
    // 核心合並循環
    for (; i < length; i++) {
        if ((options = arguments[i]) != null) {
            for (name in options) {
                src = target[name];
                copy = options[name];
                
                // 防止循環引用
                if (target === copy) continue;
                
                // 深度合並: 純對象或數組遞歸合並
                if (deep && copy && (jQuery.isPlainObject(copy) || 
                    (copyIsArray = jQuery.isArray(copy)))) {
                    
                    if (copyIsArray) {
                        copyIsArray = false;
                        clone = src && jQuery.isArray(src) ? src : [];
                    } else {
                        clone = src && jQuery.isPlainObject(src) ? src : {};
                    }
                    
                    // 遞歸調用 extend 合並
                    target[name] = jQuery.extend(deep, clone, copy);
                
                // 淺拷貝: 直接賦值 (undefined 不覆蓋)
                } else if (copy !== undefined) {
                    target[name] = copy;
                }
            }
        }
    }
    return target;
};

五大核心用法場景

1. 合並普通對象 (配置選項)


var defaults = { timeout: 3000, retry: 3, cache: true };
var options = { timeout: 5000, debug: true };

var config = $.extend({}, defaults, options);  // 不修改 defaults
// { timeout: 5000, retry: 3, cache: true, debug: true }

2. 擴展 jQuery 靜態方法 (工具函數)


$.extend({
    formatMoney: function(val) {
        return '¥' + val.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    },
    getUrlParam: function(name) {
        var match = RegExp('[?&]' + name + '=([^&]*)').exec(location.search);
        return match ? decodeURIComponent(match[1]) : null;
    }
});

// 調用
$.formatMoney(1234.5);  // "¥1,234.50"
$.getUrlParam('id');

3. 擴展 jQuery 實例方法 (插件開發核心)


$.fn.extend({
    // 禁用/啟用表單
    disable: function() {
        return this.each(function() {
            this.disabled = true;
        });
    },
    enable: function() {
        return this.each(function() {
            this.disabled = false;
        });
    },
    
    // 彈窗提示插件
    toast: function(message, duration) {
        return this.each(function() {
            var $el = $(this);
            var $toast = $('
' + message + '
') .appendTo('body') .fadeIn(); setTimeout(function() { $toast.fadeOut(function() { $(this).remove(); }); }, duration || 2000); }); } }); // 使用 $('button').disable(); $('#msg').toast('操作成功!');

4. 深度合並嵌套配置


var defaults = {
    ajax: { timeout: 3000, headers: { 'X-API': 'v1' } },
    ui: { theme: 'dark', animations: true }
};

var userConfig = {
    ajax: { timeout: 5000 },  // 僅覆蓋 timeout,保留 headers
    ui: { theme: 'light' }
};

var config = $.extend(true, {}, defaults, userConfig);
// 結果:
/*
{
    ajax: { timeout: 5000, headers: { 'X-API': 'v1' } },
    ui: { theme: 'light', animations: true }
}
*/

5. 避免修改原對象 (安全合並)


var a = { x: 1 };
var b = { y: 2 };

// ❌ 修改了 a
$.extend(a, b);  
console.log(a); // { x: 1, y: 2 }

// ✅ 不修改任何原對象
var c = $.extend({}, a, b);
console.log(a); // { x: 1 }
console.log(c); // { x: 1, y: 2 }

插件開發最佳實踐模板


(function($) {
    // 默認配置
    var defaults = {
        color: 'red',
        duration: 300,
        onComplete: null
    };
    
    // 構造函數
    function Highlight(element, options) {
        this.$el = $(element);
        this.opts = $.extend({}, defaults, options);
        this.init();
    }
    
    // 原型方法
    Highlight.prototype = {
        init: function() {
            this.$el.css('background-color', this.opts.color);
        },
        flash: function() {
            this.$el.fadeOut(this.opts.duration).fadeIn(this.opts.duration, 
                this.opts.onComplete);
        }
    };
    
    // 註冊為 jQuery 插件
    $.fn.highlight = function(options) {
        return this.each(function() {
            // 防止重複初始化
            if (!$.data(this, 'plugin_highlight')) {
                $.data(this, 'plugin_highlight', new Highlight(this, options));
            }
        });
    };
    
    // 暴露構造函數供高級用法
    $.fn.highlight.Constructor = Highlight;
    
})(jQuery);

// 使用
$('.important').highlight({ color: 'yellow', duration: 500 });

常見坑點

  1. 深度合並數組:$.extend(true, [1,2], [3,4]) 結果 {0:3, 1:4, length:2} (數組視為對象),需用 concat
  2. undefined 不覆蓋:$.extend({a:1}, {a:undefined}) 保留 a:1
  3. 循環引用死循環:源碼有 target === copy 防護,但深層循環仍可能棧溢出
  4. this 指向陷阱:插件內 this 是 jQuery 對象,回調中需 .each() 遍歷

掌握 extend 機制是編寫高質量 jQuery 插件、理解 jQuery 核心架構的關鍵。

copyright © 萬盛學電腦網 all rights reserved