jQuery.extend()的實現方式及Javascript對象的深淺復制(Z)


jQuery中的extend()
  extend()函數是jQuery的基礎函數之一,作用是擴展現有的對象。例如下面的代碼: 

Html代碼    收藏代碼
  1. <script type="text/javascript" src="jquery-1.5.2.js"></script>  
  2. <script>  
  3. obj1 = { a : 'a', b : 'b' };  
  4. obj2 = {  x : { xxx : 'xxx', yyy : 'yyy' },  y : 'y' };  
  5.   
  6. $.extend(true, obj1, obj2);  
  7.   
  8. alert(obj1.x.xxx);  // 得到"xxx"  
  9.   
  10. obj2.x.xxx = 'zzz';  
  11. alert(obj2.x.xxx);  // 得到"zzz"  
  12. alert(obj1.x.xxx);  // 得帶"xxx"  
  13. </script>  


  $.extend(true, obj1, obj2)表示以obj2中的屬性擴展對象obj1,第一個參數設為true表示深復制。 
  雖然obj1中原來沒有"x"屬性,但經過擴展后,obj1不但具有了"x"屬性,而且對obj2中的"x"屬性的修改也不會影響到obj1中"x"屬性的值,這就是所謂的“深復制”了。 

淺復制的實現


  如果僅僅需要實現淺復制,可以采用類似下面的寫法: 

Javascript代碼    收藏代碼
  1. $ = {  
  2.      extend : function(target, options) {  
  3.         for (name in options) {  
  4.             target[name] = options[name];  
  5.         }  
  6.         return target;  
  7.     }  
  8. };  


  也就是簡單地將options中的屬性復制到target中。我們仍然可以用類似的代碼進行測試,但得到的結果有所不同(假設我們的js命名為“jquery-extend.js”): 

Html代碼    收藏代碼
  1. <script type="text/javascript" src="jquery-extend.js"></script>  
  2. <script>  
  3. obj1 = { a : 'a', b : 'b' };  
  4. obj2 = {  x : { xxx : 'xxx', yyy : 'yyy' },  y : 'y' };  
  5.   
  6. $.extend(obj1, obj2);  
  7.   
  8. alert(obj1.x.xxx);  // 得到"xxx"  
  9.   
  10. obj2.x.xxx = 'zzz';  
  11. alert(obj2.x.xxx);  // 得到"zzz"  
  12. alert(obj1.x.xxx);  // 得帶"zzz"  
  13. </script>  


  obj1中具有了"x"屬性,但這個屬性是一個對象,對obj2中的"x"的修改也會影響到obj1,這可能會帶來難以發現的錯誤。 

深復制的實現


  如果我們希望實現“深復制”,當所復制的對象是數組或者對象時,就應該遞歸調用extend。如下代碼是“深復制”的簡單實現: 

Javascript代碼    收藏代碼
  1. $ = {  
  2.     extend : function(deep, target, options) {  
  3.         for (name in options) {  
  4.             copy = options[name];  
  5.             if (deep && copy instanceof Array) {  
  6.                 target[name] = $.extend(deep, [], copy);  
  7.             } else if (deep && copy instanceof Object) {  
  8.                 target[name] = $.extend(deep, {}, copy);  
  9.             } else {  
  10.                 target[name] = options[name];  
  11.             }  
  12.         }  
  13.         return target;  
  14.     }  
  15. };  


  具體分為三種情況: 
  1. 屬性是數組時,則將target[name]初始化為空數組,然后遞歸調用extend; 
  2. 屬性是對象時,則將target[name]初始化為空對象,然后遞歸調用extend; 
  3. 否則,直接復制屬性。 

  測試代碼如下: 

Html代碼    收藏代碼
  1. <script type="text/javascript" src="jquery-extend.js"></script>  
  2. <script>  
  3. obj1 = { a : 'a', b : 'b' };  
  4. obj2 = {  x : { xxx : 'xxx', yyy : 'yyy' },  y : 'y' };  
  5. $.extend(true, obj1, obj2);  
  6. alert(obj1.x.xxx);  // 得到"xxx"  
  7. obj2.x.xxx = 'zzz';  
  8. alert(obj2.x.xxx); // 得到"zzz"  
  9. alert(obj1.x.xxx); // 得到"xxx"  
  10. </script>  


  現在如果指定為深復制的話,對obj2的修改將不會對obj1產生影響了;不過這個代碼還存在一些問題,比如“instanceof Array”在IE5中可能存在不兼容的情況。jQuery中的實現實際上會更復雜一些。 

更完整的實現


  下面的實現與jQuery中的extend()會更接近一些: 

Javascript代碼    收藏代碼
  1. $ = function() {  
  2.     var copyIsArray,  
  3.         toString = Object.prototype.toString,  
  4.         hasOwn = Object.prototype.hasOwnProperty;  
  5.   
  6.     class2type = {  
  7.         '[object Boolean]' : 'boolean',  
  8.         '[object Number]' : 'number',  
  9.         '[object String]' : 'string',  
  10.         '[object Function]' : 'function',  
  11.         '[object Array]' : 'array',  
  12.         '[object Date]' : 'date',  
  13.         '[object RegExp]' : 'regExp',  
  14.         '[object Object]' : 'object'  
  15.     },  
  16.   
  17.     type = function(obj) {  
  18.         return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";  
  19.     },  
  20.   
  21.     isWindow = function(obj) {  
  22.         return obj && typeof obj === "object" && "setInterval" in obj;  
  23.     },  
  24.   
  25.     isArray = Array.isArray || function(obj) {  
  26.         return type(obj) === "array";  
  27.     },  
  28.   
  29.     isPlainObject = function(obj) {  
  30.         if (!obj || type(obj) !== "object" || obj.nodeType || isWindow(obj)) {  
  31.             return false;  
  32.         }  
  33.   
  34.         if (obj.constructor && !hasOwn.call(obj, "constructor")  
  35.                 && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {  
  36.             return false;  
  37.         }  
  38.   
  39.         var key;  
  40.         for (key in obj) {  
  41.         }  
  42.   
  43.         return key === undefined || hasOwn.call(obj, key);  
  44.     },  
  45.   
  46.     extend = function(deep, target, options) {  
  47.         for (name in options) {  
  48.             src = target[name];  
  49.             copy = options[name];  
  50.   
  51.             if (target === copy) { continue; }  
  52.   
  53.             if (deep && copy  
  54.                     && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {  
  55.                 if (copyIsArray) {  
  56.                     copyIsArray = false;  
  57.                     clone = src && isArray(src) ? src : [];  
  58.   
  59.                 } else {  
  60.                     clone = src && isPlainObject(src) ? src : {};  
  61.                 }  
  62.   
  63.                 target[name] = extend(deep, clone, copy);  
  64.             } else if (copy !== undefined) {  
  65.                 target[name] = copy;  
  66.             }  
  67.         }  
  68.   
  69.         return target;  
  70.     };  
  71.   
  72.     return { extend : extend };  
  73. }();  


  首先是 $ =  function(){...}();這種寫法,可以理解為與下面的寫法類似: 

Java代碼    收藏代碼
  1. func = function(){...};  
  2. $ =  func();  

  也就是立即執行函數,並將結果賦給$。這種寫法可以利用function來管理作用域,避免局部變量或局部函數影響全局域。另外,我們只希望使用者調用$.extend(),而將內部實現的函數隱藏,因此最終返回的對象中只包含extend: 

Java代碼    收藏代碼
  1. return { extend : extend };  


  接下來,我們看看extend函數與之前的區別,首先是多了這句話: 

Java代碼    收藏代碼
  1. if (target === copy) { continue; }  

  這是為了避免無限循環,要復制的屬性copy與target相同的話,也就是將“自己”復制為“自己的屬性”,可能導致不可預料的循環。 

  然后是判斷對象是否為數組的方式: 

Java代碼    收藏代碼
  1. type = function(obj) {  
  2.      return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";  
  3. },  
  4. isArray = Array.isArray || function(obj) {  
  5.      return type(obj) === "array";  
  6.  }  

  如果瀏覽器有內置的Array.isArray 實現,就使用瀏覽器自身的實現方式,否則將對象轉為String,看是否為"[object Array]"。 

   最后逐句地看看isPlainObject的實現: 

Java代碼    收藏代碼
  1. if (!obj || type(obj) !== "object" || obj.nodeType || isWindow(obj)) {  
  2.     return false;  
  3. }  

  如果定義了obj.nodeType,表示這是一個DOM元素;這句代碼表示以下四種情況不進行深復制: 
  1. 對象為undefined; 
  2. 轉為String時不是"[object Object]"; 
  3. obj是一個DOM元素; 
  4. obj是window。 
  之所以不對DOM元素和window進行深復制,可能是因為它們包含的屬性太多了;尤其是window對象,所有在全局域聲明的變量都會是其屬性,更不用說內置的屬性了。 

  接下來是與構造函數相關的測試: 

Javascript代碼    收藏代碼
  1. if (obj.constructor && !hasOwn.call(obj, "constructor")  
  2.               && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {  
  3.       return false;  
  4.   }  

  如果對象具有構造函數,但卻不是自身的屬性,說明這個構造函數是通過prototye繼承來的,這種情況也不進行深復制。這一點可以結合下面的代碼結合進行理解: 

Javascript代碼    收藏代碼
  1. var key;  
  2. for (key in obj) {  
  3. }  
  4.   
  5. return key === undefined || hasOwn.call(obj, key);  

   這幾句代碼是用於檢查對象的屬性是否都是自身的,因為遍歷對象屬性時,會先從自身的屬性開始遍歷,所以只需要檢查最后的屬性是否是自身的就可以了。 

  這說明如果對象是通過prototype方式繼承了構造函數或者屬性,則不對該對象進行深復制;這可能也是考慮到這類對象可能比較復雜,為了避免引入不確定的因素或者為復制大量屬性而花費大量時間而進行的處理,從函數名也可以看出來,進行深復制的只有"PlainObject"。 
  如果我們用如下代碼進行測試: 

Javascript代碼    收藏代碼
  1. <script type="text/javascript" src="jquery-1.5.2.js"></script>  
  2. <script>  
  3. function O() {  
  4.     this.yyy = 'yyy';  
  5. }  
  6.   
  7. function X() {  
  8.     this.xxx = 'xxx';  
  9. }  
  10.   
  11. X.prototype = new O();  
  12.   
  13. x = new X();  
  14.   
  15. obj1 = { a : 'a', b : 'b' };  
  16. obj2 = { x : x };  
  17. $.extend(true, obj1, obj2);  
  18.   
  19. alert(obj1.x.yyy);  // 得到"xxx"  
  20. obj2.x.yyy = 'zzz';  
  21. alert(obj1.x.yyy);  // 得到"zzz"  
  22. </script>  

  可以看到,這種情況是不進行深復制的。 

  總之,jQuery中的extend()的實現方式,考慮了兼容瀏覽器的兼容,避免性能過低,和避免引入不可預料的錯誤等因素。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM