javascript 克隆对象
function clone(myObj)
{
if(typeof(myObj) != 'object') return myObj;
if(myObj == null) return myObj;
var myNewObj = new Object();
for(var i in myObj) myNewObj[i] = clone(myObj[i]);
return myNewObj;
}
{
if(typeof(myObj) != 'object') return myObj;
if(myObj == null) return myObj;
var myNewObj = new Object();
for(var i in myObj) myNewObj[i] = clone(myObj[i]);
return myNewObj;
}
由于JAVASCRIPT的对象到对象的赋值是传址的,当我需要对两个相同内容对象进行更改与比较时,我就需要把旧对象CLONE出来。
哈,特别需求,特别处理。。。以上是方法,以下是调用
var o = {a:1, b:2};
var b = o;
b.b = 3; //此时,o.b的值为3
var o = {a:1, b:2};
var b = clone(o);
b.b = 3; //此时,o.b的值仍为2
var b = o;
b.b = 3; //此时,o.b的值为3
var o = {a:1, b:2};
var b = clone(o);
b.b = 3; //此时,o.b的值仍为2