Antonio Ortiz Antonio Ortiz - 1 year ago 91
Javascript Question

In Javascript, how is this argument passed by value and not by reference?

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"

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download