Saturday, 14 September 2013

Function arguments passed by value

Function arguments passed by value

I'm reading that in JavaScript, a common point of confusion arises because
variables of primitives are passed by value, and variables of objects are
passed by reference, while in function arguments, both primitives and
references are passed by value.
In the course of my tinkering, I've made up the following code, but am
having trouble wrapping my head around it.
> function setName2(obj) {
... obj.name="matt";
... obj = new Object();
... obj.name="obama";
... }
If I set
var person = new Object();
person.name = "michelle";
Then run
> setName2(person);
I get
> person.name;
'matt'
Which makes sense because the new object created is a pointer to a local
object, hence not affecting the property of the global 'person'.
However, what if I first set
var obj = new Object();
obj.name = "michelle";
Then run
> setName2(obj);
?
I get the same outcome. Does this mean that the compiler recognizes the
two variables of the same name (obj global and obj local) as references to
different locations within the heap, each having some different pointer
association, or is there a different explanation for this phenomenon?

No comments:

Post a Comment