PDA

View Full Version : Copy Object 'by value' not 'by reference'?


robkar97
12-15-2008, 12:26 PM
How do you make an independent copy of an Object?

Eg

var a = new Object();
a.value = 1;

var b=a;
alert(b.value) // shows "1"

a.value= 5;

alert(b.value) //shows "5"... but I want it to remain 1 :eek:

tnowalk
12-15-2008, 04:21 PM
When 'copying' variables from one object to another it is assigned by reference, meaning that both variables point to the same object. To truly copy objects you must fire up a function that physically copies each variable to the new object using a for...in loop.


function copyObject(object) {
var r = new Object();

for (var e in object) {
r[e] = object[e];
}
return r;
}

var a = new Object();
a.value = 1;

var b=copyObject(a);
alert(b.value) // shows "1"

a.value= 5;

alert(b.value)


If you have any questions feel free to pm me!
Trevor

robkar97
12-15-2008, 05:55 PM
Ok, I get it. Thanks!

Jon Hanlon
12-18-2008, 04:58 PM
function cloneObject(obj) {
for (i in obj) {
if (typeof obj[i] == 'object')
this[i] = new cloneObject(obj[i]);
else
this[i] = obj[i];
}
}