2

Is it possible to create a function enumerateScope() that lists all properties (keys) of the current scope?

<script>
var a = "foo";
enumerateScope(); //all properties of global window object including 'a'
</script>

this is pretty easy, but what about this?

<script>
(function(){
   var b = "bar";
   enumerateScope(); //either only 'b' or all properties of global window object including 'b'
})();
</script>

The last case is what I am interested in. I don't want to change any code inside the anonymous / closure scope just like

(function(scope){scope.b = "bar";})(window);

Is there any way to achieve this?

muffel
  • 7,004
  • 8
  • 57
  • 98
  • possible duplicate of [Getting All Variables In Scope](http://stackoverflow.com/questions/2051678/getting-all-variables-in-scope) – James Allardice Jun 28 '13 at 12:45

2 Answers2

2

Sorry, it's not possible. Variable declarations create bindings to the current execution context's environment record, which is not something you have access to.

See "Declaration Binding Instantiation" in the spec for the details.

See also the section on execution context (emphasis added):

An execution context is purely a specification mechanism and need not correspond to any particular artefact of an ECMAScript implementation. It is impossible for an ECMAScript program to access an execution context.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
2

Well, this isn't impossible in the strict sense, consider

bindings = function() {
    var v = String(bindings.caller).match(/\w+/g).join(" ");
    return "('"+v+"'.split(' ').reduce(function($1,$2){try{$1[$2]=eval($2)}finally{return $1}},{}))";
}


vars = (function(){
    var b = "bar";
    var foo = "quux";
    return eval(bindings())
})();

console.log(vars) 
//{
// "b": "bar",
// "foo": "quux"
//}

but I wouldn't call it practical in most cases, except, maybe, for debugging purposes.

georg
  • 211,518
  • 52
  • 313
  • 390
  • It doesn't look like it would work for non-primitives, also you are parsing javascript with the regex `\w+` which hardly looks like it would work anything but something you carefully crafted. – Esailija Jun 28 '13 at 13:40