In Javascript, I'm used to being able to access variables within a known namespace "dynamically" (correct me if I'm using the wrong word here) by using the []
operator. For instance (from the global namespace):
var a = 1;
window['a']; # => 1
Or from a object-type namespace:
var a = { b: 1 };
a['b']; # => 1
And I'm familiar with the basics of how this
is determined:
var a = function(){ return this['c']; };
var b = { c: 1 };
a.apply(b); # => 1;
But within a function itself, how do I access local variables I've just instantiated (or redefined) using var
?
Namely, I want the following function call to return 1
but without calling a
:
function(){
var a = 1;
return a;
}
You can't use window['a']
because a
is defined locally, and you can't use this['a']
because this
changes depending on the context from which the function is called.
In a realistic setting, I'd simply refactor to avoid dynamically creating and accessing local variables because it's generally a bad idea anyway, but as an academic question, I'm curious as to whether it's possible to access a
via its string name at all.