Is it possible to send a link to a global variable to a function in JavaScript? This answer says no, but I cannot believe, there is no workaround.
What I mean is something like the following. It is not working, but it shall explain what I mean:
var data_1;
var data_2;
fillValue(data_1,"First");
fillValue(data_2,"Second");
function fillValue(link2GlobalVar, value){
link2GlobalVar = value;
}
console.log(data_1);
console.log(data_2);
It would be great if it was possible to output in the console
First
Second
Do you know a trick to send global variables to functions and change them within them like this?
See Fiddle
Primitive values aren't passed by reference. Objects are.
If you wrap the globals in an object, you'll be able to modify its properties from a function:
Other than that,
this
, should be more portable thanwindow
. (Works both in the browser and onnodejs
). You can't use it from inside functions (that aren't called with new) if you're in strict mode, but you can use it in global scope to get a reference to the global scope.