Get The Name Property Of A Variable
I was wondering if it's possible to get the name of a variables in javascript or JQuery. Suppose that I declare a variable in javascript like: var customerNr = '456910'; If a func
Solution 1:
That is simply not possible!
The passed parameter doesn't even have to have a name. It could be a return value of a function or a raw literal (like "string"
or 3
).
Solution 2:
No, this is not possible. Only values are transferred for primitive data types, not references, so how would you know what the "name" of the variable is? For example:
var customerNr="456910";
var customerNrAfterProcessing=customerNr;
getNameOfVariable(customerNrAfterProcessing);
Would it return customerNrAfterProcessing
or customerNr
?
However, you can imitate this behavior with objects.
var variableName = someMethodThatDeterminesVariableNameOrJustAConstantIfYouPrefer();
var myVariables={};
var myVariables[variableName]={};
myVariables[variableName].value="456910";
myVariables[variableName].variableName=variableName;
functiongetNameOfVariable(someVariable){
return someVariable.variableName;
}
getNameOfVariable(myVariables[variableName]);
Obviously, this amounts to a lot more work than just using the variableName variable directly, but it could be necessary in some more complicated situations.
Post a Comment for "Get The Name Property Of A Variable"