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
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
Share Improve this question edited Apr 28, 2011 at 20:01 Herman Schaaf 48.5k21 gold badges105 silver badges140 bronze badges asked Apr 28, 2011 at 19:58 Doua BeriDoua Beri 10.9k18 gold badges95 silver badges143 bronze badges 2- possible duplicate of javascript how to create reference – Quentin Commented Apr 28, 2011 at 19:59
- @David Dorwad actually I'm looking for the opposite thing. How to pass objects as value and not as refference – Doua Beri Commented Apr 28, 2011 at 20:02
4 Answers
Reset to default 6You 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
This may be of use:
http://my.opera./GreyWyvern/blog/show.dml/1725165
obj1
and obj2.m
point to the same object. You cannot have obj1.m1 != obj2.m.m1
What you can do is assign a copy of obj1
to obj2.m
. See the link Will posted.
you need to clone it first.
Object.prototype.clone = function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i == 'clone') continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
} else newObj[i] = this[i]
} return newObj;
};
var obj1={ m1:"a", m2:"b" };
var obj2={ m: {}};
obj2.m = obj1.clone();
obj2.m.m1="c";
document.write(obj2.m.m1+"<br>");
document.write(obj1.m1+"<br>");