使对象不通过引用传递
我刚刚发现在 Javascript 中通过引用传递对象是很困难的,例如:
for(var layer = 0; layer < hudLayers['layers'].length; layer++){
// Store the to-be-calculated values in this object
var tempValues = hudLayers['layers'][layer];
tempValues['name'] = 'test';
}
这将更改 tempValues 和 hudLayers 中的值。 (似乎很明显,但是没有一点代码的帖子看起来很赤裸裸。)
有没有快速解决这个问题的方法?
I just found out the hard way objects are passed by reference in Javascript, for example:
for(var layer = 0; layer < hudLayers['layers'].length; layer++){
// Store the to-be-calculated values in this object
var tempValues = hudLayers['layers'][layer];
tempValues['name'] = 'test';
}
This will change the value in tempValues and hudLayers.
(Seems kind of obvious, but a post without a bit of code seems so naked.)
Is there a quick way around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是通过引用传递的示例(您没有传递任何参数)。
然而,你是对的;分配对象不会进行深层复制。
您可以像这样制作对象的深层副本:
请注意,如果对象的构造函数有任何副作用,则此代码将触发它们。
This is not an example of passing by reference (you aren't passing any parameters).
However, you're correct; assigning an object will not make a deep copy.
You can make a deep copy of an object like this:
Note that if an object's constructor has any side-effects, this code will trigger them.
JavaScript 中没有引用传递。对象是通过引用访问的,这些引用是按值分配或传递的,就像在 Java 中一样
There is no pass by reference in JavaScript. Objects are accessed through references and those references are assigned or passed passed by value, just like in Java
制作对象的深层复制就像
objCopy = obj.toSource();
一样简单。MDN 上的 .toSource
Making a deep copy of an object is as simple as
objCopy = obj.toSource();
..toSource on MDN