Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript passing variable as value and not as reference

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

like image 829
Doua Beri Avatar asked Feb 16 '26 11:02

Doua Beri


1 Answers

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
like image 59
Anthony Mills Avatar answered Feb 19 '26 00:02

Anthony Mills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!