0

Possible Duplicate:
JavaScript Pass Variables Through Reference

How can you do something like this in javascript?

In PHP you can put a & in a function in front of the parameter to write directly back to the variable.. How can you do something like this in javascript?

Community
  • 1
  • 1
clarkk
  • 27,151
  • 72
  • 200
  • 340

2 Answers2

2

In JavaScript, values are passed to functions by value. Objects, however, are passed by reference.

Passing values:

function myfunction(x)
{
      // x is equal to 4
      x = 5;
      // x is now equal to 5
}

var x = 4;
alert(x); // x is equal to 4
myfunction(x); 
alert(x); // x is still equal to 4

Passing objects:

function myobject()
{
    this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
    fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6

Source: http://snook.ca/archives/javascript/javascript_pass

Rémi Breton
  • 4,209
  • 2
  • 22
  • 34
  • 1
    The specific difference is that the `x = 5` line in the first example is discarding the original parameter value of `x` and replacing it with `5`. In the second example the `fnc` variable is not replaced in this way so the original object that was passed in will be updated. – Gareth Feb 24 '12 at 16:55
0

If you pass an object into a function it is always treated as passing a reference to it. To have a similar effect for primitive values, you might wrap them in an object before like

 var intVal = { val: 0 };

That way you can pass it to a function and still modify the actual variable.

Sirko
  • 72,589
  • 19
  • 149
  • 183