I want to be able to modify the arguments passed to a self executing function.
Here is some sample code:
var test = 'start';
(function (t) {t = 'end'} )(test);
alert(test) //alerts 'test'
And here is a fiddle. The variable test
has not changed. How can I alter it, as in pass-by-reference?
You cannot do that (well, precisely that) in JavaScript. You can do something like this, however:
JavaScript only has pass-by-value in function calls; there's only one corner-case way to have an alias to something like a variable (the
arguments
object and parameters), and it's sufficiently weird to be uninteresting.That said, object properties are (usually) mutable, so you can pass object references around in cases where you need functions to modify values.
You can't do this.
The best you can do is pass in an object, and then update that object.
Pass in an
object
, it is pass-by-reference:FYI,
Array
is also pass-by-reference.you are just passing the value of test variable as an argument to the function. After changing the argument's value you need to assign back to the test variable.
Or