0

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. 
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
lorenzo
  • 15
  • 1
  • 3
  • Just curious, where do you need this ? Thanks – Mahesh Velaga Dec 10 '09 at 13:35
  • The javascript code is autogenerated. If I knew the answer of my question I would be able to add up at the end of a function a bit of code which would validate some assumptions made by the code generator. – lorenzo Dec 10 '09 at 13:38
  • I *wish* this was possible. Oh I so wish. – Crescent Fresh Dec 10 '09 at 13:59
  • Do you need to know all defined variables or just whether a specific one is defined? The latter **can** be done, the first AFAIK not. – akuhn Dec 10 '09 at 16:23
  • @Adrian: I don't think it can, you can't get at the execution context's variable object to do the `in` operation, and if you check the name to see if its value is `undefined`, that doesn't differentiate between no `var` at all vs. having the `var` but it having the value `undefined` (because you never assigned to it, or at some point assigned `undefined` explicitly). If it's possible, I'd love to know how, that'd be cool. – T.J. Crowder Dec 11 '09 at 10:24

2 Answers2

1

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.

nes1983
  • 15,209
  • 4
  • 44
  • 64
1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875