0

I have someone's code which sets the name of a new Object.

function setName(human) { 
    human.name = "Nicholas";
    human = new Object();
    human.name = "Greg";
};

var newPerson = new Object(); 
setName(newPerson); 
console.log(newPerson.name);

I want to use the value of the property 'name' of the person object.

I was expecting the value to be 'Greg' but I am getting 'Nicholas'.

This is my understanding: 'human' is a pointer to an Object. When the function is called, another pointer to the same Object would be created by the name of newPerson.

The 'name' property of the newPerson Object would be set to 'Nicholas'. Then, another newPerson object is created in the second line of the function. Hence, the first instance should be destroyed. Then, the 'name' property of this new Object would be set to 'Greg'. Where am I going wrong?

Amit Saxena
  • 216
  • 5
  • 15

2 Answers2

5

Think of variables with object values as handles to these objects.

var newPerson = new Object(); 

You created a new object and a handle to it called newPerson.

setName(newPerson);

function setName(human) { 

When setName is called, newPerson is copied into human. So now you have two handles that refer to the same object. It so happens that both of them are actually accessible inside the function, but this doesn't really matter to the discussion.

    human.name = "Nicholas";

The object referred to by human has a new name. Since human and newPerson are still handles to the same object, newPerson.name has now changed as well.

    human = new Object();

Now the handles diverge. newPerson still continues to be a handle to Nicholas, but human becomes a handle to the new object.

    human.name = "Greg";

And this new object's name is Greg. This does not affect Nicholas in any way.

};

console.log(newPerson.name);

newPerson is still a handle to Nicholas.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

human is local variable for function.

human = new Object();

After this line you have new object for local variable human but not for that variable which you sent to function as argument

It means that you sent arguments to function by value.

For example in C# you can use keywork ref which will make funciton working as you expected.

Alexey
  • 59
  • 7