Greg Woods
Greg Woods

Reputation: 2770

Why is my javascript argument not passed "by reference"?

I'm sure I'm missing something obvious here, but I'd expect the argument to the changeMe method to be passed "by reference" - in other words, that changes to the parameter inside the function will change the variable outside the function.

The following was run in jsfiddle, using Chrome's F12 developer tools to show the console output. http://jsfiddle.net/fzEpa/

var object1 = { Property1: 'Value1' };
changeMe(object1);
console.log(object1);

function changeMe(refToObject) {
    console.log(refToObject);
    refToObject = { Property1: 'Value2' };
    console.log(refToObject);
}

Upvotes: 1

Views: 199

Answers (4)

Fabrício Matté
Fabrício Matté

Reputation: 70199

A reference to the object is passed as the argument value. However:

refToObject = { Property1: 'Value2' };

At this point you lose the reference to the object formerly referenced by refToObject as you're assigning this variable to reference a different object.

Now if you were to edit the refToObject's properties instead of discarding the former object reference, your code would work as exepected (as firstly explained in @Quentin's answer).

Upvotes: 3

Quentin
Quentin

Reputation: 944426

It is passed by reference, but it is a reference to the object, not to the object1 variable (which is also a reference to the object).

You are overwriting the reference to the object with a reference to a new object.

This leaves the original reference to the original object intact.

To modify the object, you would do something like this:

function changeMe(refToObject) {
    refToObject.Property1 = 'Value2';
}

Upvotes: 11

dreamweiver
dreamweiver

Reputation: 6002

you are trying to redefine the Property 1,so it wouldnt work. in order to work with pass by reference ypu have to do it this way refToObject.Property1='Value2' inside your ChangeMe() function . refer this for better understanding Pass Variables by Reference in Javascript

Upvotes: 0

Tomer Arazy
Tomer Arazy

Reputation: 1823

If you're familiar with C++ this would be equal to doing something like this:

void f(int* ref) {
    ref = new int(3);
}
int* a = new int(5);
f(a);
printf("%d",a); //Prints 5

Upvotes: 0

Related Questions