3

Is there a way to locate all variables inside a scope? e.g.

var localScope = function() {
    var var1 = "something";
    var var2 = "else...";

   console.log(LOCAL_SCOPE);
};

where LOCAL_SCOPE so returns an object like:

{
    var1: "something",
    var2: "else..."
}

I know a can do this by making a local object. but i seek a way to locate all variables without having any idea of them existing.

5
  • 2
    is this a question resulting from an issue you are having? If so, please also put in that question
    – Rene Pot
    Commented Nov 1, 2011 at 8:32
  • This isn't possible. What do you need this for?
    – thejh
    Commented Nov 1, 2011 at 8:32
  • Questions don't go in answers. Commented Nov 1, 2011 at 8:33
  • This is the best answer that's possible unless he adds context to the question.
    – thejh
    Commented Nov 1, 2011 at 8:35
  • The first sentence, perhaps; it would be borderline due to its short size. But combine that with your question and it becomes a conversation. Commented Nov 1, 2011 at 8:36

1 Answer 1

1

There's no reliable way to obtain all local variables. The closest you can get is by obtaining the source of the function.

If you don't know a reference to the current function (eg name), you have to use the deprecated (and forbidden in ECMAScript 5) argument.callee.

When you've got a reference to the function, you have to obtain the string of the source, either by the non-standard toSource() method, or .toString().

After the string is obtained, you have to get all variable names, eg, by using a RegExp. Combining this method with looping through window, you can get all local variables of functions which are defined in the global scopes. Then, eval (!!!) has to be used to get a reference to the local variables.


In short, you should not attempt to look for a method which locates all local variables, because there's no reliable way to achieve this.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.