I have a Function
in which I want to retrieve the name of the variable that was used to call the function. How can I do that?
let fooVar = 3;
let barVar = "hello World";
function doStuff(variable) {
let varName = ???; // retrieve name of variable
return varName + ": " + variable;
}
document.write(doStuff(fooVar)); // should output "fooVar: 3"
document.write(doStuff(barVar)); // should output "barVar: hello World"
If variable
was a Function
, I could use variable.name
.
I am aware of this, but it will only return "variable"
, not the name of the variable that was put into the function.
As an alternative: Is there a way to AUTOMATICALLY call a certain function whenever a variable is declared? If that was possible, I'd use the approach given in the link above to add the variable name to a map, then utilize that map inside the function to retrieve variable name.
Aucun commentaire:
Enregistrer un commentaire