5

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.

Steven
  • 17,796
  • 13
  • 66
  • 118
  • 2
    See http://stackoverflow.com/questions/598878/how-can-i-access-local-scope-dynamically-in-javascript and http://stackoverflow.com/questions/2336508/javascript-get-access-to-local-variable-or-variable-in-closure-by-its-name and http://stackoverflow.com/questions/1119335/javascript-local-variable-declare – Roatin Marth Feb 23 '11 at 18:04

1 Answers1

3

You're mixing up local variables (which are not properties of an object) with properties (which are not local variables). There is no answer to your question, or, rather, the answer is "it can't be done".

jmbucknall
  • 2,061
  • 13
  • 14