简体   繁体   中英

Access the outer scope's variables via bracket notation

Obviously an inner function can access the outer scope's variables, eg

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

var name = 'Dave';
example();

Is it possible to access that variable with bracket notation? eg

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM