JavaScript中並無直接提供對象複製(Object Clone)的方法。所以下面的代碼中改變對象b的時候,也就改變了對象a。javascript
a = {k1:1, k2:2, k3:3}; b = a; b.k2 = 4;
若是隻想改變b而保持a不變,就須要對對象a進行復制。java
在能夠使用jQuery的狀況下,jQuery自帶的extend
方法能夠用來實現對象的複製。this
a = {k1:1, k2:2, k3:3}; b = {}; $.extend(b,a);
下面的方法,是對象複製的基本想法。spa
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)。prototype
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."); }