Object reference issue

放肆的年华 提交于 2019-12-24 15:15:02

问题


I am facing a strange problem in JavasSript.

There are three variables (declared as var), they all store an object; say var object1, object2 and object3.

Ok, so what I do now is I assign object2=object1 and object3=object1.

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.


回答1:


So how is that strange?

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".




回答2:


When you assign opject2 = object1, you are not making a copy of object1, you are simply asking that both names refer to the same object. You need to make a new object and copy the attributes from object1 into it. How you do that depends on what Javascript libraries you have available to you.

jQuery provides copying techniques described here



来源:https://stackoverflow.com/questions/9341159/object-reference-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!