Modify arguments in self executing function

吃可爱长大的小学妹 提交于 2019-12-06 05:41:15

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.

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.

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'

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!