为什么在 JavaScript 中会发生这种情况?
今天我在javascript中遇到了这个问题,不知道为什么会发生。
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 ¿?
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 ¿?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
表达式
{ prop: ... }
表达式计算一次即可创建一个对象。a
和b
都是对该单个对象的引用。请参阅通过引用传递与通过引用传递之间有什么区别按值传递? 和 http://en.wikipedia.org/wiki/Reference_(computer_science)
编辑
clone
from underscore 会进行浅复制。要创建深层副本,最简单的方法可能是序列化和反序列化。如果
a
有引用循环,这会做奇怪的事情。The expression
{ prop: ... }
expression is evaluated once to create one object.a
andb
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)
EDIT
clone
from underscore does a shallow copy.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.您已创建对同一对象的引用。执行此操作时,变量 b 的任何更改都会影响变量 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.
当您将 b 分配给 a 时,分配是通过引用进行的,这意味着 b 引用内存中与 a 相同的位置,因此当 b 更新并且您观察到 a 时,看起来 a 也已更新。
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.