Search code examples
javascriptvariablesscopelocaldetect

Locate variables in scope?


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.


Solution

  • 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.