Getting All Variables In Scope

2018-12-31 14:52发布

Is there a way to get all variables that are currently in scope in javascript?

标签: javascript
9条回答
何处买醉
2楼-- · 2018-12-31 15:43

You can't.

Variables, identifiers of function declarations and arguments for function code, are bound as properties of the Variable Object, which is not accesible.

See also:

查看更多
像晚风撩人
3楼-- · 2018-12-31 15:44

If you just want to inspect the variables manually to help debug, just fire up the debugger:

debugger;

Straight into the browser console.

查看更多
还给你的自由
4楼-- · 2018-12-31 15:49

In ECMAScript 6 it's more or less possible by wrapping the code inside a with statement with a proxy object. Note it requires non-strict mode and it's bad practice.

function storeVars(target) {
  return new Proxy(target, {
    has(target, prop) { return true; },
    get(target, prop) { return (prop in target ? target : window)[prop]; }
  });
}
var vars = {}; // Outer variable, not stored.
with(storeVars(vars)) {
  var a = 1;   // Stored in vars
  var b = 2;   // Stored in vars
  (function() {
    var c = 3; // Inner variable, not stored.
  })();
}
console.log(vars);

The proxy claims to own all identifiers referenced inside with, so variable assignments are stored in the target. For lookups, the proxy retrieves the value from the proxy target or the global object (not the parent scope). let and const variables are not included.

Inspired by this answer by Bergi.

查看更多
登录 后发表回答