lorenzo
lorenzo

Reputation: 15

How to find the variables defined in a function

Suppose I have a long javascript function such as

function test() {
    var x; 
    var a;
    ...
    ...
    ...
    ...
    ...
}

is there any way I can ask the function itself to tell me what variables were defined so far.

function test() {
   var x; 
   var a;
   ...
   ...
   ...
   ...
   ... // bit of code that would say to me: x and a. 
}

Upvotes: 0

Views: 153

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075337

No, not without relying on Function#toString and then performing string processing on the result, which is not recommend. Function#toString is implemented by most browsers as giving you the source code of the function (with or without comments, depending), but isn't standardized by the spec (even the latest) and I wouldn't use it in production code.

Upvotes: 1

nes1983
nes1983

Reputation: 15756

That would require reflection. But Javascript comes without very much any reflection support. I don't think you can do it, except like this: parse your own function.

Upvotes: 1

Related Questions