1

Obviously an inner function can access the outer scope's variables, e.g.

function example() {
    console.log('My name is ' + name);
}

var name = 'Dave';
example();

Is it possible to access that variable with bracket notation? e.g.

function example() {
    console.log('My name is ' + outerScope['name']);
}

(For those of you wondering why I want to do this, it's for a potential debugging technique, not actual production code).

maxedison
  • 17,243
  • 14
  • 67
  • 114
  • possible duplicate of [JavaScript: Reference a functions local scope as an object](http://stackoverflow.com/questions/2600361/javascript-reference-a-functions-local-scope-as-an-object) – doldt Aug 06 '15 at 20:28

1 Answers1

2

No, that's impossible. Scopes are no objects accessible from JS code, and don't have properties.

You can use eval though if you want to access variables by their name with a string. Alternatively, you should check whether your runtime has a debugging API that you could use, it will typically expose such information.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Can you provide an example of how I'd use `eval` in this case? Such as in my `example()` function above? – maxedison Aug 06 '15 at 20:26
  • `console.log('My name is ' + eval('name'))` should do (of course it uses normal identifier resolution, you cannot access shadowed variables or variables on a specific scope). – Bergi Aug 06 '15 at 20:27
  • Great! That achieves what I was aiming for. – maxedison Aug 06 '15 at 20:29
  • 1
    Doing that is terrible though. If you want a bunch of named variables that you access with the variable name in a string: bundle them up as properties of an object. – Quentin Aug 06 '15 at 20:34
  • 2
    @Quentin: Of course it is. I trusted OP to only use this to explore "*a potential debugging technique*". – Bergi Aug 06 '15 at 20:36