This is not possible in Javascript, because the objects where the variables are stored (Environment Records) are not available to the language user except in the case of the global object. But even in this case, listing the properties of the global object will include all global variables, not just the ones you created. For example:
var a = 10;
for(i in window) {
if(window.hasOwnProperty(i)) console.log(i)
}
Output will include your variable a
, but also includes document
, localStorage
, name
, etc..
You can partially circumvent this problem by passing on the object arguments
from one function to the other. 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.
This could be really interesting.
– Carlos Cinelli