Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this happen in javascript?

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 ¿?
like image 278
Datamosh Avatar asked May 09 '26 21:05

Datamosh


1 Answers

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));
like image 163
Mike Samuel Avatar answered May 11 '26 10:05

Mike Samuel



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!