萬盛學電腦網

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

jQuery.extend() 深度解析:從淺拷貝到深拷貝的實現原理與最佳實踐

前言

jQuery.extend() 是 jQuery 核心工具方法之一,廣泛用於物件合併、選項配置、插件參數預設值處理等場景。它支援淺拷貝與深拷貝兩種模式,理解其內部機制有助於避免常見的引用共享陷阱,並能在需要時實現自訂的合併邏輯。

基本用法回顧

// 淺拷貝:$.extend(target, object1, object2, ...)
var obj1 = { a: 1, b: { x: 10 } };
var obj2 = { b: { y: 20 }, c: 3 };
$.extend(obj1, obj2);
// 結果:obj1 = { a: 1, b: { y: 20 }, c: 3 }
// 注意:obj1.b 與 obj2.b 指向同一個物件

// 深拷貝:$.extend(true, target, object1, ...)
$.extend(true, obj1, obj2);
// 結果:obj1.b 為新物件,修改 obj2.b 不影響 obj1.b

淺拷貝的簡易實現

淺拷貝僅遍歷來源物件的可枚舉屬性,直接將值賦予目標物件:

var $ = {
  extend: function(target, options) {
    for (var name in options) {
      target[name] = options[name];
    }
    return target;
  }
};

缺點:當屬性值為物件或陣列時,目標與來源共享同一引用,修改其中一者會影響另一者。

深拷貝的遞歸實現

深拷貝需針對陣列與純物件遞歸建立新實例:

extend: function(deep, target, options) {
  for (var name in options) {
    var copy = options[name];
    if (deep && copy instanceof Array) {
      target[name] = $.extend(deep, [], copy);
    } else if (deep && copy instanceof Object) {
      target[name] = $.extend(deep, {}, copy);
    } else {
      target[name] = copy;
    }
  }
  return target;
}

此版本仍有缺陷:instanceof Array 在跨 iframe 或舊版 IE 中不可靠;未處理循環引用;未排除 DOM 節點、window 等不應深拷貝的特殊物件。

jQuery 核心實現精華解析

jQuery 內部採用立即執行函數封裝私有工具函數,僅暴露 extend 方法:

var $ = (function() {
  var class2type = {},
    toString = Object.prototype.toString,
    hasOwn = Object.prototype.hasOwnProperty;

  // 精確類型判斷
  var type = function(obj) {
    return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";
  };

  var isArray = Array.isArray || function(obj) {
    return type(obj) === "array";
  };

  // 判斷純物件(排除 DOM、window、自定義建構函數)
  var isPlainObject = function(obj) {
    if (!obj || type(obj) !== "object" || obj.nodeType || isWindow(obj)) return false;
    if (obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) return false;
    var key;
    for (key in obj) {}
    return key === undefined || hasOwn.call(obj, key);
  };

  var extend = function(deep, target, options) {
    for (var name in options) {
      var src = target[name],
        copy = options[name];

      // 防止循環引用:target 試圖包含自己
      if (target === copy) continue;

      // 深拷貝條件:deep 為真 且 copy 為純物件或陣列
      if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
        if (copyIsArray) {
          copyIsArray = false;
          clone = src && isArray(src) ? src : [];
        } else {
          clone = src && isPlainObject(src) ? src : {};
        }
        target[name] = extend(deep, clone, copy);
      } else if (copy !== undefined) {
        target[name] = copy;
      }
    }
    return target;
  };

  return { extend: extend };
})();

關鍵設計細節

  1. 類型判斷:使用 Object.prototype.toString.call() 而非 instanceof,解決跨框架、IE 兼容問題。
  2. 純物件檢測:isPlainObject 排除 null、非物件、DOM 節點、window、以及繼承自自定義建構函數的物件(如 new MyClass())。
  3. 循環引用保護:if (target === copy) continue; 防止無限遞歸。
  4. 保留現有結構:若目標已有同類型結構(陣列/物件),復用它而非重建,減少記憶體分配。
  5. undefined 跳過:copy !== undefined 確保不將 undefined 寫入目標,保持原屬性不變。

實戰建議與常見坑

  • 合併多個來源:$.extend(true, {}, obj1, obj2, obj3) 以空物件為目標,避免汙染原物件。
  • 陣列合併行為:深拷貝時陣列會被整體替換,而非逐項合併。若需陣列去重或合併,請自行處理。
  • 非純物件:Date、RegExp、Function 等會被直接賦值(引用),不進行深拷貝。
  • 效能考量:大型物件樹深拷貝成本高,必要時才開啟 deep=true。

總結

jQuery.extend() 以嚴謹的類型檢測、循環引用防護、純物件判定,實現了健壯的深/淺拷貝。理解其核心邏輯,不僅能正確使用,更能在框架設計、狀態管理(如 Redux reducer)、配置合併等場景舉一反三。

copyright © 萬盛學電腦網 all rights reserved