1

Am new to client side application development, need some clarity on below mentioned issue.

I have one object var obj1={'name':'Sachin'}

I assign that object to obj2

var obj2=obj1.

Now my obj2 and obj1 objects both are same

Now by using obj2 I change the name property value like

obj2.name="Dravid";

Now my obj1 and obj2 both name property values turned to be 'Dravid' because of 'sigletone' behavior of JSON object? is it correct?

Now my question is:

if I made my obj1 is empty like

   obj1={}

then why my obj2 is not turned to be empty ?

still it show obj2={'name':'Dravid'}

What is the reason behind that ?

Could please help me on this.

thanks in advance...


user1632949
  • 615
  • 3
  • 9
  • 18

2 Answers2

2

I believe that when you make the first assignment, obj1 and then assign obj1 to obj2, you are copying a shared reference to the same position in memory. Then when you assign the empty { } to obj1, you are creating a new object in memory, replacing the other reference. At that point obj1 and obj2 have different references

Matt
  • 879
  • 9
  • 29
0

In Javascript Objects are passed as references. So obj1 and obj2 are referencing the same object when you make changes you only change one object referenced by 2 variables. If you assign obj1 to another object, it has no affect on the reference on obj2.

Tsumiqt
  • 83
  • 5