我有一个拥有大量数据的大物体。我想将其克隆到其他变量中。当我设置实例B的某些参数时,在原始对象中具有相同的结果:
var obj = {a: 25, b: 50, c: 75};
var A = obj;
var B = obj;
A.a = 30;
B.a = 40;
alert(obj.a + " " + A.a + " " + B.a); // 40 40 40
我的输出应该是25 3040。有什么想法吗?
编辑
感谢大家。我更改了dystroy的代码,这是我的结果:
Object.prototype.clone = Array.prototype.clone = function()
{
if (Object.prototype.toString.call(this) === '[object Array]')
{
var clone = [];
for (var i=0; i<this.length; i++)
clone[i] = this[i].clone();
return clone;
}
else if (typeof(this)=="object")
{
var clone = {};
for (var prop in this)
if (this.hasOwnProperty(prop))
clone[prop] = this[prop].clone();
return clone;
}
else
return this;
}
var obj = {a: 25, b: 50, c: 75};
var A = obj.clone();
var B = obj.clone();
A.a = 30;
B.a = 40;
alert(obj.a + " " + A.a + " " + B.a);
var arr = [25, 50, 75];
var C = arr.clone();
var D = arr.clone();
C[0] = 30;
D[0] = 40;
alert(arr[0] + " " + C[0] + " " + D[0]);
相关分类