I've noticed this behavior when writing my JavaScript, and I haven't been able to figure out why:
Below is some code to reproduce the behavior in question.
var o1 = {
num: 1
}
var o2 = o1;
o2.num = 2;
alert(o1.num);
Expected Result: The browser alerts 1, because I only changed a property of the o2 object, not the o1 object.
Actual Result: The browser alerts 2, because it seems o1 is equal to o2.
I'm not really sure what's going on. How can I fix the code so it alerts 1 rather that 2 (assuming that o1 hasn't changed)?
Much thanks in advance.
Because both variables reference the same object. Objects are not cloned/copied on variable assignment. You would have to do this yourself.
JavaScript behaves the same way like any (most) other OO languages in this case.
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