This is not possible in JavaScript, because objects where variables are stored ( environment records ) are not available to the language user except in the case of the global object. But even then, listing the properties of the global object will include all the global variables, not just the ones you've created. For example:
var a = 10;
for(i in window) {
if(window.hasOwnProperty(i)) console.log(i)
}
The output will include its a
variable, but also includes document
, localStorage
, name
, etc.
You can partially work around this problem by passing the% object arguments
from one function to another. For example:
function soma(a, b) {
return a + b;
}
function subtrai(a, b) {
return a - b;
}
function somaOuSubtrai(a, b) {
// Transforma os argumentos de objeto para array, esperada pelo apply.
// Não é 100% necessário, mas garante compatibilidade com implementações antigas
var args = Array.prototype.slice.call(arguments);
if(a >= b) {
return subtrai.apply(null, args);
} else {
return soma.apply(null, args);
}
}
somaOuSubtrai(1,3); // 4
somaOuSubtrai(3,1); // 2
Another alternative is to package your variables as properties of an object (a namespace ), as suggested by @Sergio. In the end, you may end up using a combination of these strategies.