DIV CSS 佈局教程網

jQuery.extend() 的實作原理詳解與範例
編輯:關於JavaScript     

複製程式碼 程式碼如下:

<script type="text/javascript" src="jquery-1.5.2.js"></script>
<script>
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"
</script>

$.extend(true, obj1, obj2) 表示以 obj2 的屬性擴展 obj1,第一個參數設為 true 代表「深複製」。雖然 obj1 原本沒有 x 屬性,但擴展後不但有了 x,而且對 obj2 中 x 的修改也不會影響到 obj1 的 x,這就是所謂的深複製。

淺複製的實作

如果只需要淺複製,可以用類似下面的寫法:

複製程式碼 程式碼如下:

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

也就是簡單地把 options 的屬性複製到 target。用相同測試會發現,obj1 雖然有了 x 屬性,但這是個物件,對 obj2 中 x 的修改也會連帶影響 obj1,這可能帶來難以發現的錯誤。

深複製的實作

若希望做到深複製,當複製的屬性是陣列或物件時就應該遞歸呼叫 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 在 IE5 中可能不相容,jQuery 的實作會更複雜。

更完整的實作

下面的實作與 jQuery 中的 extend() 更接近:

複製程式碼 程式碼如下:

$ = 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。接著 extend 中多了 if (target === copy) { continue; },用來避免「自己複製成自己的屬性」造成的無限循環。判斷陣列時,若瀏覽器有內建的 Array.isArray 就使用,否則轉字串看是否為 "[object Array]"。

isPlainObject 則逐層把關:若為 undefined、轉字串後不是 "[object Object]"、是 DOM 元素或 window,都不做深複製(因為它們屬性太多、風險高);再檢查 constructor 是否為自身屬性、以及屬性是否皆為自身所有,只有「純物件」才會被深複製。

總之,jQuery 的 extend() 實作充分考虑了瀏覽器相容性、效能與避免引入不可預期錯誤等因素,是一部值得細讀的經典。

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