Modify arguments in self executing function

2019-05-20 03:30发布

问题:

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?

回答1:

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.



回答2:

You cannot do that (well, precisely that) in JavaScript. You can do something like this, however:

 var testBox = { test: "hello" };
 (function(tb) { tb.test = "goodbye"; })(testBox);
 alert(testBox.test); // "goodbye"

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.



回答3:

You can't do this.

The best you can do is pass in an object, and then update that object.

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


回答4:

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.

var test = 'start';
(function (t){t = 'end'; test = t;} )(test);
alert(test) //alerts 'test'

Or

var myObject = {test: "start"};
var myFunc = function (theObject){
    theObject.test = 'end';
}(myObject);
alert(myObject.test);