The most "similar" way of simulating the send by reference way that I found is accessing the context of the parent scope sending the reference of the var name as a string:
var undefinedVar, undefinedVar2, undefinedVar3;
function init() {
for(var i=0; i<arguments.length; i++){
this[arguments[i]] = new Function();
}
}
init('undefinedVar', 'undefinedVar2', 'undefinedVar3');
This can be useful for example initializing or validating arguments inside a function.
For example instead of having to repeat code like this
(function myContext(arg1, arg2, arg3){
if(!arg1 || (typeof(arg1)!='function')){
arg1 = new Function();
}
if(!arg2 || (typeof(arg1)!='function')){
arg2 = new Function();
}
if(!arg3 || (typeof(arg1)!='function')){
arg3 = new Function();
}
console.log(arguments);
})()
we could do the following
function init(context) {
for(var i=1; i<arguments.length; i++){
if(!context[arguments[i]] || (typeof(arg1)!='function'))
(context[arguments[i]] = new Function());
}
}
(function myContext(arg1, arg2, arg3){
init(arguments, 'arg1', 'arg2', 'arg3');
console.log(arguments);
})()
This prints
arg1:ƒ anonymous() arg2:ƒ anonymous() arg3:ƒ anonymous()
This helps to avoid duplicity of code in this kind of situations.