javascriptpass-by-referenceanonymous-functionself-executing-function

Modify arguments in self executing function


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?


Solution

  • Pass in an object, it is pass-by-reference:

    var test = {
        message: 'start'
    };
    (function (t) {t.message = 'end'} )(test);
    alert(test.message)
    

    FYI, Array is also pass-by-reference.