Since you are using .NET , briefly talk about it. In C #, you can create a function that accepts Expression
:
void BadArgument<T>(Expression<Func<T>> argExpr) { }
But in order to be able to extract the variable name from the call to this function, you need to make sure that the call always uses the correct syntax (although this is not possible during compilation);
if(x < 0) BadArgument(() => x);
So it can be done, but very fragile and rather slow. You basically generate instructions to create an entire expression tree based on the lambda () => x
expression, so the function you call can parse that expression tree and try to find the name of the argument.
Can this be done in javascript? Of course!
In javascript, closures are done through internal functions, so the equivalent of the above lambda expression would be:
function(){return x;}
And since javascript is a scripting language, each function is equivalent to its own definition as a string. In other words, calling .toString()
for the specified function will give:
function(){return x;}
This jsfiddle shows how you can use this in a logging style function. Then you can parse the result string of the function, which will only have a bit more problems than parsing the .NET expression tree. Moreover, getting the actual value of x
even easier than in .NET: you just call the function !
But just because you can do it does not mean that you should. . It's nice, like a gee-whiz-style trick, but when it comes to it, it's not worth it:
- This is fragile: what if some developer does not use it correctly and gives you a function that you cannot analyze?
- This does not work with minimization: imagine that you received a message that the variable
a
had the wrong value, because your minified function changed your variable names. - It adds overhead: even a minifier cannot reduce
function(){return x;}
less than "x"
. - Finally, it is difficult. - he said.
source share