可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I\'ve got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don\'t know how to explain it any better than that, so see if this example makes sense.
function getVariableName(unknownVariable){
return unknownVariable.originalName;
}
getVariableName(foo); //returns string \"foo\";
getVariableName(bar); //returns string \"bar\";
This is for a jquery plugin i\'m working on, and i would like to be able to display the name of the variable which is passed to a \"debug\" function.
回答1:
You\'re right, this is very much impossible in any sane way, since only the value gets passed into the function.
回答2:
This is now somehow possible thanks to ES6:
function getVariableName(unknownVariableInAHash){
return Object.keys(unknownVariableInAHash)[0]
}
const foo = 42
const bar = \'baz\'
console.log(getVariableName({foo})) //returns string \"foo\"
console.log(getVariableName({bar})) //returns string \"bar\"
The only (small) catch is that you have to wrap your unknown variable between {}
, which is no big deal.
回答3:
Well, all the global variables are properties of global object (this or window), aren\'t they?
So when I wanted to find out the name of my variables, I made following function:
var getName = function(variable) {
for (var prop in window) {
if (variable === window[prop]) {
return prop;
}
}
}
var helloWorld = \"Hello World!\";
console.log(getName(helloWorld)); // \"helloWorld\"
Sometimes doesn\'t work, for example, if 2 strings are created without new operator and have the same value.
回答4:
Global w/string method
Here is a technique that you can use to keep the name and the value of the variable.
// Set up a global variable called g
var g = {};
// All other variables should be defined as properties of this global object
g.foo = \'hello\';
g.bar = \'world\';
// Setup function
function doStuff(str) {
if (str in g) {
var name = str;
var value = g[str];
// Do stuff with the variable name and the variable value here
// For this example, simply print to console
console.log(name, value);
} else {
console.error(\'Oh snap! That variable does not exist!\');
}
}
// Call the function
doStuff(\'foo\'); // log: foo hello
doStuff(\'bar\'); // log: bar world
doStuff(\'fakeVariable\'); // error: Oh snap! That variable does not exist!
This is effectively creating a dictionary that maps variable names to their value. This probably won\'t work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.
ES6 object method
In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.
function getVariableName(unknownVariable) {
return Object.keys(unknownVariable)[0];
}
var foo = \'hello\';
var output = getVariableName({ foo }); // Note the curly brackets
console.log(output);
This works because you created a new object with key foo
and value the same as the variable foo, in this case hello
. Then our helper method gets the first key as a string.
Credit goes to this tweet.
回答5:
Converting a set of unique variable into one JSON object for which I wrote this function
function makeJSON(){ //Pass the variable names as string parameters [not by reference]
ret={};
for(i=0; i<arguments.length; i++){
eval(\"ret.\"+arguments[i]+\"=\"+arguments[i]);
}
return ret;
}
Example:
a=b=c=3;
console.log(makeJSON(\'a\',\'b\',\'c\'));
Perhaps this is the reason for this query
回答6:
As you want debugging (show name of var and value of var),
I\'ve been looking for it too, and just want to share my finding.
It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.
It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it :
var foo = \'bar\'
debug(\'foo\') // print \"foo is bar\"
function debug(Variable) {
var Value = this[Variable.replace(/\'/g,\"\")] // we remove the quotes
// \"this[]\" allow the function to consider what is between brackets as a variable
print(Variable + \" is \" + Value) // print \"foo is bar\"
}