JavaScript:将对象存储为固定值?
我在编写 JavaScript 时注意到了这种行为,但我一直无法找出原因:
下面是一些重现相关行为的代码。
var o1 = { num: 1 } var o2 = o1; o2.num = 2; alert(o1.num);
预期结果:浏览器警告1,因为我只更改了o2对象的属性,而不是o1对象。
实际结果:浏览器警告2,因为看起来o1等于o2。
我不太确定发生了什么事。如何修复代码,使其警报 1 而不是 2(假设 o1 没有更改)?
非常感谢。
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);
Expected Result: The browser alerts 1, because I only changed a property of the o2 object, not the o1 object.
Actual Result: The browser alerts 2, because it seems o1 is equal to o2.
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)?
Much thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为两个变量引用同一个对象。变量分配时不会克隆/复制对象。 您必须自己执行此操作。
在这种情况下,JavaScript 的行为方式与任何(大多数)其他 OO 语言相同。
Because both variables reference the same object. Objects are not cloned/copied on variable assignment. You would have to do this yourself.
JavaScript behaves the same way like any (most) other OO languages in this case.
通过编写
var o2 = o1;
,您将创建o1
和o2
对同一对象的两个引用。您想要做的是克隆o1
对象并将克隆的副本存储在o2
中。在 JavaScript 中搜索克隆对象。By writing
var o2 = o1;
you're makingo1
ando2
two references to the same object. What you want to do is to clone theo1
object and to store the cloned copy ino2
. Search for cloning objects in JavaScript.因为您将对象设置为相同的参考点。您需要克隆该对象。这是来自 http://www.thespanner 的一段代码.co.uk/2008/04/10/javascript-cloning-objects/ 允许通过原型克隆对象。
Because you are setting the objects to the same reference point. You need to clone the object. here is a piece of code from http://www.thespanner.co.uk/2008/04/10/javascript-cloning-objects/ that allows for cloning of objects with prototyping.