Getting All Variables In Scope

前端 未结 10 2357
小蘑菇
小蘑菇 2020-11-22 09:10

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

10条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 09:50

    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.

提交回复
热议问题