views:

33

answers:

3

In the scenario below, how can I get references to the variables declared during eval() if I do not know their names?

function test() {
  eval("var myVariable = 5");
  var locals = magic() // TODO What should we do here?
  alert(locals["myVariable"]); // returns myVariable
}

Just a note: JavaScript being evaluated comes from a trusted source.

+1  A: 

eval() runs in the same scope as the caller, so this will work:

function test() {
  eval("var myVariable = 5");
  var locals = {};
  locals.myVariable = myVariable; // TODO What should we do here?
  alert(locals["myVariable"]); // returns myVariable
}

But you can't determine what variables were declared in the eval() call (if that's what you want)

Philippe Leybaert
+1  A: 
function test() {
  eval("var locals = {myVariable: 5};");
  alert(locals["myVariable"]);
}

works for me. eval() does not create a new scope.

Tomalak
I've clarified the question to point out that I do not know the names of those variables beforehand.
David Parunakian
+1  A: 

Simple as :

eval("var myVariable = 5");
//no magic is needed
alert(myVariable); // returns myVariable
Khnle
What if I don't know the variables' names? I.e. I need to find out their names first.
David Parunakian