In ECMAScript 6 it's more or less possible by wrapping the code inside a with
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.