javascript list all declared variables 1

javascript list all declared variables

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);
 Run code snippetHide results

Here is what the above code is Doing:
1. The storeVars function returns a proxy that intercepts all property accesses.
2. The proxy’s has trap returns true for all properties, so the with statement doesn’t throw a ReferenceError.
3. The proxy’s get trap returns the value of the property from the target object if it exists, otherwise it returns the value of the property from the global object.
4. The with statement executes the code in its body, which assigns values to a and b.
5. The with statement finishes, and the proxy is garbage collected.
6. The vars object contains the values of a and b.

Similar Posts