Is there a way to get the variable name, like you can do in .Net with reflection?
like in this scenario:
function(x,y,z)
{
if (x === 0)
logger.log('variable ' + x.reflectedName ' has invalid value ' + x)
// logs: 'variable x has invalid value 0)
...
}
I found similar questions that wanted the name of the var outside of the function(?!) but couldn't find this question.
(jQuery is an option, though I can't think how it can be done with it...)
You can't. But since you already know the variable name (since you have to use it to concatenate it to the end of the string), why not just type it in?
ie.:
It is easy to get the variable name
also you can try in here.
Edited
Thanks for the comment @Brady
Object.keys({variableName})[0] will give you the variable name.
Actually you
CAN
. Here is a snippet:The other problem is if you create some vars that contain the same variable. Then first var will be returned.
Since you're using .NET as an example, let's delve briefly into that. In C#, you could create a function that takes an
Expression
:But in order to be able to extract the variable name from a call to this function, you would have to make sure the call always uses exactly the right syntax (even though there is no way to enforce this at compile time):
So it can be done, but it's very fragile and pretty slow. You're basically generating instructions to create a whole expression tree based on the lambda expression
() => x
, just so the function you call can parse out that expression tree and try to find the name of the argument.Can this sort of thing be done in javascript? Sure!
In javascript, closures are produced via internal functions, so the equivalent of the above lambda expression would be:
And since javascript is a scripting language, each function is the equivalent of its own definition as a string. In other words, calling
.toString()
on the above function will yield:This jsfiddle shows how you can leverage this in a logging-style function. You are then free to parse the resulting function string, which will be only slightly more trouble than parsing the .NET Expression Tree would be. Furthermore, getting the actual value of
x
is even easier than in .NET: you just call the function!But just because you can do it doesn't mean you should. It's nice as a gee-whiz parlor trick, but when it comes right down to it, it's not worth it:
a
had an incorrect value because your minified function changed your variable names.function(){return x;}
to be smaller than"x"
.