开发者

Getting references to local variables created during eval() in JavaScript

In the scenar开发者_C百科io 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.


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)


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

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


Simple as :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜