0

I was wondering if it is possible to access a variable (i.e. get the value of that variable) by using the name of that variable. An example would be:

function myObject(){
   var x = 1;
   this.get = function(varName){return eval(varName);};
}
var test = new myObject();
test.get("x");

I know this is possible with eval, but I was wondering if the same could be done without the use of eval, like i.e. with Function. (The use of eval is not allowed in the framework I'm using.)

JasperTack
  • 4,337
  • 5
  • 27
  • 39

1 Answers1

0

You can access global variables as an associative array, like this:

var x = 5;
var variableName = "x";
window[variableName];

In your case, you can return this[varName], if you replace var x with this.x.

Meredith
  • 844
  • 6
  • 17
  • 1
    This would indeed be a solution for the globally defined variables. However, I would like to only access the locally defined variables (in this case x). – JasperTack May 05 '14 at 01:57
  • This is the only way to do it. Just use this.x or write out your accessors. – Meredith May 05 '14 at 02:04
  • 2
    There are no associative arrays in javscript, there are just objects (even arrays are basically plain objects with a special *length* property and some mostly generic methods). And *this* references a real object, it has nothing to do with variables. – RobG May 05 '14 at 02:05