开发者

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 f开发者_运维问答alse ¿?


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));


You've created a reference to the same object. When you do this, any changes of variable b will affect the object stored in variable a.

You will need to do a 'clone' of the object to change it so you have two objects instead of one with two references.


when you assign b to a the assignment is by reference meaning b references the same location in memory as a so when b is updated and you observe a it looks like a is also updated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜