问题描述
我在 JavasSript 中遇到了一个奇怪的问题.
I am facing a strange problem in JavasSript.
共有三个变量(声明为var
),它们都存储一个对象;比如说 var object1
、object2
和 object3
.
There are three variables (declared as var
), they all store an object; say var object1
, object2
and object3
.
好的,我现在要做的是分配 object2=object1
和 object3=object1
.
Ok, so what I do now is I assign object2=object1
and object3=object1
.
当我向 object2
添加内容时,它会自动添加到 object3
.奇怪的?:|
And when I add something to object2
, it automatically gets added to object3
. Strange? :|
请帮忙.我想我在这里缺少一些基本的基础,但我无法抓住它.
Please help. I think I am missing some basic funda here, but I am not able to catch it.
推荐答案
那有什么奇怪的?
您传递对对象的引用并且不要克隆该对象.因此,对变量 object1 到 object3 的任何修改实际上都指向同一个对象,从而自动更新所有变量".
You pass reference to the object and do not clone the object. So any modification of your variables object1 to object3 actually refer to the same object, thus "automatically updating all variables".
这篇关于对象引用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!