简体   繁体   English

获取输入变量的名称(如 Function.name)

[英]get name of input variable (like Function.name)

I have a Function in which I want to retrieve the name of the variable that was used to call the function.我有一个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 .如果variableFunction ,我可以使用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.我知道这一点,但它只会返回"variable" ,而不是放入函数中的变量的名称。


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.如果可能的话,我会使用上面链接中给出的方法将变量名称添加到映射中,然后在函数内部利用该映射来检索变量名称。

That's actually impossible to do, as a workaround you can do something like this这实际上是不可能做到的,作为一种解决方法,您可以执行以下操作

 let fooVar = { name: 'fooVar', value: 3 }; let barVar = { name: 'barVar', value: 'Hello World' }; function doStuff({ name, value }) { let varName = name; // retrieve name of variable return varName + ": " + value; } console.log(doStuff(fooVar)); // should output "fooVar: 3" console.log(doStuff(barVar));

or you can do或者你可以做

 let fooVar = 3; let barVar = 'Hello World'; function doStuff(variable) { const arr = Object.entries(variable)[0]; const [name, value] = arr; let varName = name; // retrieve name of variable return varName + ": " + value; } console.log(doStuff({ fooVar })); // should output "fooVar: 3" console.log(doStuff({ barVar }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM