2

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.

3
  • Do you have any ability to affect what that code you're passing to eval() looks like? In other words, can you change that code at all in order to make this work, or are you stuck with code coming from another source, and you cannot change it? Commented Jun 16, 2010 at 14:34
  • I can alter the code; what do you propose? Commented Jun 16, 2010 at 14:37
  • 1
    Well if you can make the code explicitly declare an object with a predictable name, and then put other (unpredictable) properties inside that object (see @tomalak's answer), then you can use that. But eval() does not create a new scope, and as far as I know there's no way to get a reference to your local "closure" scope in a way that'd let you treat it like an object. Commented Jun 16, 2010 at 14:41

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

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

1 Comment

I've clarified the question to point out that I do not know the names of those variables beforehand.
1

Simple as :

eval("var myVariable = 5");
//no magic is needed
alert(myVariable); // returns myVariable

1 Comment

What if I don't know the variables' names? I.e. I need to find out their names first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.