开发者

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

开发者 https://www.devze.com 2023-01-03 12:11 出处:网络
In the scenar开发者_C百科io below, how can I get references to the variables declared during eval() if I do not know their names?

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

精彩评论

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

关注公众号