简体   繁体   English

Javascript - 获取变量的名称

[英]Javascript - Getting the name of the variable

When i call a function in javascript with a variable, for example:当我用一个变量在 javascript 中调用一个函数时,例如:

CheckFunction(MyVariable);
CheckFucntion(MyVariable2);

And i have a function which, for example, checks if it's a number or not:我有一个函数,例如,检查它是否是一个数字:

function CheckFunction(SOURCE){
//THE CODE ITSELF
};

I wanna log with the name of the original variable, how could i get that?我想用原始变量的名称登录,我怎么能得到它? I can get the name "SOURCE" with the code below:我可以使用以下代码获得名称“SOURCE”:

Object.keys({SOURCE})[0])

But i'd like to log with the original name( MyVariable ) from the called function.但我想使用被调用函数的原始名称( MyVariable )登录。

Sample output in the console:控制台中的示例输出:

Area is a number.面积是一个数字。

Where Area is a integer variable, and its name got checked from CheckFunction() function.其中Area是一个整数变量,它的名字是从 CheckFunction() 函数中检查出来的。

This is not possible in Javascript without any third-party tools to analyze the code.如果没有任何第三方工具来分析代码,这在 Javascript 中是不可能的。 Variables will not hold where they have been / come from.变量不会保存它们曾经/来自何处。

The best you can do is what you already have with Object.keys({SOURCE})[0]) This is because you are converting the variable to a key and then reading the key again.你能做的最好的事情就是你已经拥有的Object.keys({SOURCE})[0])这是因为你正在将变量转换为一个键,然后再次读取该键。

You would need a method on the variable to get the name as a string.您需要在变量上使用一个方法来将名称作为字符串获取。


A better solution would be to send another parameter to the function with its location.更好的解决方案是向函数发送另一个参数及其位置。 ie . IE 。 CheckFunction(myVariable, 'onLoad); . . Alternatively, you could send an object with more verbose information that will help you track what you need.或者,您可以发送一个包含更详细信息的对象,以帮助您跟踪所需内容。

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

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