问题描述
我在编写JavaScript时已经注意到了这种行为,我无法弄清楚原因:
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);
预期结果:浏览器提醒1,因为我只更改了 o2的属性对象,而不是 o1 对象。
Expected Result: The browser alerts 1, because I only changed a property of the o2 object, not the o1 object.
实际结果:浏览器提醒2,因为它似乎 o1 等于 o2 。
Actual Result: The browser alerts 2, because it seems o1 is equal to o2.
我不确定发生了什么。如何修复代码,使其提醒1而不是2(假设 o1 未更改)?
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)?
非常感谢提前。
推荐答案
因为两个变量引用 相同的对象。不在变量赋值上克隆/复制对象。 。
Because both variables reference the same object. Objects are not cloned/copied on variable assignment. You would have to do this yourself.
在这种情况下,JavaScript的行为与任何(大多数)其他OO语言相同。
JavaScript behaves the same way like any (most) other OO languages in this case.
这篇关于JavaScript:将对象存储为固定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!