0

Please explain why changing a global objects string property in local scope does affect the property in a global scope but giving a new value to the whole object doesn't.

In my example, the first time I run changeMyName function, I get what I'm expecting - a change in my_global_object.name value.

But why doesn't the second time I run the function change the my_global_object object to my_global_object.children.first_child object?

var my_global_object=new Object();
my_global_object.name='my parent name'
my_global_object.children=new Object();
my_global_object.children.first_child=new Object();
my_global_object.children.first_child.name='my first child name';

function changeMyName(child_name,new_name){
    var my_local_object;
    my_local_object=my_global_object;
    if(child_name) my_local_object=my_local_object.children[child_name];
    my_local_object.name=new_name;  
}

changeMyName(false,'new parent name'); 

changeMyName('first_child','new first child name');

Why is this "=" assignment

if(child_name) my_local_object=my_local_object.children[child_name];

different from this "=" ?

my_local_object.name=new_name;  

Is there a some sort of a "giving a value" and "passing a refrence" difference?

Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39
  • Please explain your first line . Where did you change the global object in your code ? – AllTooSir Apr 17 '13 at 09:14
  • Inside the changeMyName function I assing the global object to the local object and change the value of it's name property. If I log the my_global_object after that, it has the name I've passed on to the function. – Jaak Kütt Apr 17 '13 at 09:21

1 Answers1

1
 my_local_object=my_global_object;

Assigning the reference of the object referred by variable my_global_object to the variable my_local_object here . So now both variables refer to the same object .

my_local_object.name=new_name;

Updating the name property of the object , which is referenced by both variables my_global_object and my_local_object , hence my_global_object.name will be same as my_local_object.name.

my_local_object=my_local_object.children[child_name];

Assigning the variable my_local_object reference to the object referred to by my_local_object.children[child_name] . So now my_local_object variable doesn't point to the object referred by my_global_object variable .

AllTooSir
  • 48,828
  • 16
  • 130
  • 164