I am trying to wrap my head around this idea of 'argument passing.' In a book I am reading it states that arguments are only passed by value not by reference.
function addTen(num) {
num + = 10;
return num;
}
var count = 20;
var result = addTen(count);
alert(count); // 20 - no change
alert(result); // 30
The example above is pretty clear, but the example below leaves me very confused.
When person is passed to the setName function, doesn't it mirror the local variable 'obj' and flow down the statements in the function? i.e. person is first set to the property name, then it's assigned to a new Object, and finally this new created person object is assigned the property 'Gregg'????
Why do you get 'Nicholas'!!!!
function setName(obj) {
obj.name = "Nicholas";
obj = new Object();
obj.name = "Greg";
}
var person = new Object();
setName(person);
alert(person.name); //" Nicholas"
Objects are passed to function as a copy of the reference. Now what happens in your example is next:
var person = new Object();
function setName(obj) { // a local obj* is created, it contains a copy of the reference to the original person object
obj.name = "Nicholas"; // creates a new property to the original obj, since obj here has a reference to the original obj
obj = new Object(); // assigns a new object to the local obj, obj is not referring to the original obj anymore
obj.name = "Greg"; // creates a new property to the local obj
}
setName(person);
alert( person.name); //" Nicholas"
* = obj is a local variable containing a value, which is a reference to the original obj. When you later change the value of the local variable, it's not reflecting to the original object.
You get "Nicholas" precisely because JavaScript is never "by reference". If it was, you'd be able to update the person variable from any location. That's not the case, so the new Object() in the function doesn't mutate the outer person variable.
But it's also not the case that variables refer to the objects themselves, but rather variables hold a special type of reference that let you update the object without directly accessing the memory.
That's why although JavaScript is always "by value", you never get a full copy of an object. You're merely getting a copy of that special reference. As a result, you can manipulate the original object passed via the copy of the reference, but you can't actually replace it via the reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With