How does JS get the variable name (reflection)

  node.js, question

JS how to get the variable name when the program executes.

For example, a function returns the parameter name of the specified parameter.

jsVar paramName = 'asdf' // whatever it is.
 var paramName2 = new Object();  //Whatever it is.
 function getParamName(p) {
 //... implementation process
 var result = ...;  //This is only a simulation
 return result;

The return result of the final parameter should be:


Excuse me, how can similar requirements be realized and are there any alternative methods?

I looked at it and felt’s quite reasonable.

2017.1.5 Answers Rewritten

Each context has a corresponding variable object, and any declared variable is an attribute of this variable object. The variable object of the global context is a global object, so the variables declared in the global become the attributes of the global object. Correspondingly, the variable object of the function context is the activated object, and the variable declared in the function context is the attribute of the activated object. However, the activation object is an object inside the engine and cannot be accessed externally, so the name of the function context variable cannot be obtained in JS.

In addition, the basic type of function argument is passed into the function by way of value, and the object type argument is passed into the function by way of reference. Either way, the function can only obtain the passed-in value or reference, and cannot access the variable object of the calling function’s context, so the name of the variable of the passed-in function cannot be obtained inside the function.

Since no function can return the name of the variable in the context calling this function and JS does not provide an operator that can do this, it is impossible to obtain the name of the variable inside the execution context.

Of course, for the execution context of the function code, if we can get the code of this function, we can parse this code to get the names of the variables in this code.

Sample code:

function getParamName() {}
 function fn() {
 var param1 = 0
 var a = 2
 function callWithVariableName(fn) {
 Eval ('('plus fn.tostring (). replace (\ bgetparamname \ s * \ ([a-za-z _ $] [\ w _ $] *) \)/g, function (u, v) {
 Return "'"plus v plus "'"
 }) plus' ())')

Console output: