DIV CSS 佈局教程網

深入 jQuery.extend():淺拷貝與深拷貝的實現原理全解析
編輯:JavaScript綜合知識     

extend() 是 jQuery 的基礎函數之一,作用是「擴展現有的對象」,也就是我們常說的物件合併與拷貝。它看似簡單,但要正確處理「深拷貝」卻大有學問。本文從基礎用法一路深入,帶你看懂 jQuery 是如何實現 extend 的。

基礎用法與深拷貝演示

obj1 = { a : 'a', b : 'b' };
obj2 = { x : { xxx : 'xxx', yyy : 'yyy' }, y : 'y' };

$.extend(true, obj1, obj2);

alert(obj1.x.xxx); // 得到 "xxx"

obj2.x.xxx = 'zzz';
alert(obj2.x.xxx); // 得到 "zzz"
alert(obj1.x.xxx); // 得到 "xxx"

$.extend(true, obj1, obj2) 表示以 obj2 的屬性擴展 obj1,第一個參數設為 true 代表「深拷貝」。可以看到,即使 obj1 原本沒有 x 屬性,擴展後不僅有了,而且對 obj2 中 x 的修改完全不會影響到 obj1——這就是深拷貝的效果。

淺拷貝的實現

如果只需要淺拷貝,寫法非常簡單:

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

也就是直接把 options 的屬性逐一複製到 target。此時若測試,你會發現:obj1 雖然有了 x 屬性,但這個屬性是一個「引用」,對 obj2.x 的修改會連帶影響到 obj1.x,這可能帶來難以發現的 bug。

深拷貝的實現

要實現深拷貝,當所複製的屬性是陣列或物件時,就應該「遞歸」呼叫 extend:

$ = {
  extend : function(deep, target, options) {
    for (name in options) {
      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] = options[name];
      }
    }
    return target;
  }
};

具體分三種情況:屬性是陣列時,初始化為空陣列再遞歸;屬性是物件時,初始化為空物件再遞歸;否則直接複製。不過這個版本仍有缺陷,例如 instanceof Array 在舊版 IE 中可能不相容。

更完整的實現(貼近 jQuery 原始碼)

下面的實現與 jQuery 真正的 extend() 更為接近,加入了型別判斷、isPlainObject 檢查等健壯性處理:

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

  class2type = {
    '[object Boolean]' : 'boolean',
    '[object Number]' : 'number',
    '[object String]' : 'string',
    '[object Function]' : 'function',
    '[object Array]' : 'array',
    '[object Date]' : 'date',
    '[object RegExp]' : 'regExp',
    '[object Object]' : 'object'
  },

  type = function(obj) {
    return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";
  },

  isWindow = function(obj) {
    return obj && typeof obj === "object" && "setInterval" in obj;
  },

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

  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);
  },

  extend = function(deep, target, options) {
    for (name in options) {
      src = target[name];
      copy = options[name];
      if (target === copy) { continue; }
      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 };
}();

這個版本有幾個值得逐一拆解的細節:

首先是 $= function(){...}(); 這種「立即執行函數」寫法,它利用 function 管理作用域,避免局部變數污染全域,同時只對外暴露 $.extend(),把內部實作函數藏起來。

接著是 if (target === copy) { continue; } 這句,用意是避免無限循環——若屬性 copy 就是 target 自己(把「自己」複製為「自己的屬性」),可能導致不可預料的循環。

然後是型別判斷:若瀏覽器有內建的 Array.isArray 就用它,否則把物件轉成字串看是否為「[object Array]」。

最後是 isPlainObject 的逐句解析:若物件為 undefined、轉字串後不是「[object Object]」、是 DOM 元素(有 nodeType)或是 window,則不進行深拷貝——因為這些物件屬性太多、太複雜,深拷貝既耗時又易出錯。而與構造函數相關的檢查,則是為了排除那些「透過 prototype 繼承而來構造函數」的物件,只對真正的「純物件」(PlainObject)做深拷貝。

總的來說,jQuery 的 extend() 在實現時,綜合考慮了瀏覽器相容性、性能開銷,以及避免引入不可預期錯誤等多重因素,因此才會比我們直覺想像中的「簡單合併」複雜得多。理解這些細節,你對 JavaScript 物件拷貝的認識也會更上一層樓。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved