Modify arguments in self executing function

2019-05-20 02:59发布

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?

4条回答
不美不萌又怎样
2楼-- · 2019-05-20 03:20

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.

查看更多
你好瞎i
3楼-- · 2019-05-20 03:28

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楼-- · 2019-05-20 03:37

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.

查看更多
何必那么认真
5楼-- · 2019-05-20 03:37

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);
查看更多
登录 后发表回答