1. 程式人生 > >JavaScript中的物件複製(Object Clone)

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);
        var obj1 = {
		apple: 0,
		banana: {weight: 52, price: 100},
		cherry: 97
	};
	var obj3;
	obj3 = $.extend(true, obj1, obj3);
	console.log(obj1 === obj3);//true
	obj3.apple = 3;
	console.log(obj1 === obj3);//true
	obj3 = $.extend(true, {}, obj1);
	console.log(obj1 === obj3);//false

Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend(). If, however, you want to preserve both of the original objects, you can do so by passing an empty object as the target:

1

var object = $.extend({}, object1, object2);

方法物件不需要複製也不會存在引用的問題

if(requestObj.error){
		errorCallback = requestObj.error;
	}
	
//	console.log(requestObj.error === errorCallback);//true
	requestObj.error = function(req, msg, err){
		console.log(requestObj.url);
		console.log(req);
		console.log(msg);
		console.log(err);
		if(errorCallback){
//			console.log(requestObj.error === errorCallback);//false
			errorCallback(req, msg, err);
		}
		
		if(dialogConfirm.dialog( "isOpen" )){
			dialogConfirm.dialog('close');
		}
		$('#confirmMsg').text(err);
		$('.confirm-buttons').hide();
		$('#btnOk').show();
		dialogConfirm.dialog('open');
		$('#btnOk').unbind('click');
		$('#btnOk').on('click', function() {
			dialogConfirm.dialog('close');
			return false;
		});
	}
//	console.log(requestObj.error === errorCallback);//false

自定義clone()方法來實現物件複製

下面的方法,是物件複製的基本想法。

Object.prototype.clone = function() {
  var copy = (this instanceof Array) ? [] : {};
  for (attr in this) {
    if (!obj.hasOwnProperty(attr)) continue;
    copy[attr] = (typeof this[i] == "object")?obj[attr].clone():obj[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.");
}