JavaScript中的對象複製(Object Clone)

JavaScript中並沒有直接提供對象複製(Object Clone)的方法。因此下面的代碼中改變對象b的時候,也就改變了對象a。

a = {k1:1, k2:2, k3:3};
b = a;
b.k2 = 4;

如果只想改變b而保持a不變,就需要對對象a進行復制。

用jQuery進行對象複製

 

在可以使用jQuery的情況下,jQuery自帶的extend方法可以用來實現對象的複製。

a = {k1:1, k2:2, k3:3};
b = {};
$.extend(b,a);
 

自定義clone()方法來實現對象複製

下面的方法,是對象複製的基本想法。

Object.prototype.clone=function(){
   var copy=(this instanceof Array) ? [] :{};
   for(var attr in this){
       if(!this.hasOwnProperty(attr)) continue;
       copy[attr]=(typeof this[attr] == "object") ? this[attr].clone(): this[attr];
   }
   return copy;
};


a = {k1:1, k2:2, k3:3};
b = a.clone();

下面的例子則考慮的更全面些,適用於大部分對象的深度複製(Deep Copy)。

function clone(obj) {
    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        var copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        var copy = [];
        for (var i = 0, var len = obj.length; i < len; ++i) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        var copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}
發佈了30 篇原創文章 · 獲贊 6 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章