Today I came across this problem in javascript and do not know why it happens.
var a = {
prop: {
bool: true
}
};
console.log(a.prop.bool); // logs true
var b = a;
b.prop.bool = false;
console.log(a.prop.bool); // logs false ¿?
The expression { prop: ... } expression is evaluated once to create one object.
a and b both are references to that single object.
See What's the difference between passing by reference vs. passing by value? and http://en.wikipedia.org/wiki/Reference_(computer_science)
References are widely used in programming, especially to efficiently pass large or mutable data as arguments to procedures, or to share such data among various uses.
EDIT
clone from underscore does a shallow copy.
Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.
To create a deep copy, the easiest way is probably to serialize and deserialize. This will do weird things if a has reference cycles though.
var b = JSON.parse(JSON.stringify(a));
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