My problem is simple I think, but I couldn't find a simple solution to it. Here is the example:
var obj1 = {
m1:"a",
m2:"b"
};
var obj2 = {
m:obj1
};
obj2.m.m1 = "c";
document.write(obj2.m.m1+"<br>"); //output: c
document.write(obj1.m1+"<br>"); // output: c ( I wanted to be a)
So.. what do I need to do to return "a" from obj1.m1 ?
Thanks in advance
You need to set obj2.m to a clone of obj1, not obj1 itself. For instance:
function clone(obj) {
var result = {};
for (var key in obj) {
result[key] = obj[key];
}
return result;
}
var obj2 = {
m: clone(obj1)
};
obj2.m.m1 = "c"; // does not affect obj1.m1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With