Can't eval break statement

删除回忆录丶 提交于 2019-12-24 00:25:46

问题


Why is this piece of code :

    var myBreak = 'break;';
    for(var i=0; i < 5; i++) {
        console.log('i is : ' + i);
        eval(myBreak);
    }
    console.log('done !');

triggering the :

unlabelled break must be inside loop or switch

error message in Firebug in place of returning done ! in the console ?

Is it not possible to eval() break statements ?

Thank you in advance !

EDIT :

I'm getting confused now. ^^

  • Why does it fail ?
  • Is Jack Wanders right then with eval having it's own 'execution context' ?
  • If yes, why isn't his example working ?

回答1:


eval parses/evaluates code in a new instance of the JavaScript interpreter. The code eventually executes in context with the original interpreter's code but the code has to be able to execute without that external context because the new instance is blind to it.

So alert(eval(this.constructor.name)) will give you the proper object context name (window in global).

But these will fail because the instances don't 'see' each other's code until it's been evaluated by the separate interpreters and at this phase one piece fails without the other:

  • try{}eval('catch(){}');

  • for(;;){ eval('break;'); }

  • myLoop: eval('for(;;){ break myLoop; }');

Short version: Code will work as expected but anything in an eval would have to be something you could fire in any other context by itself.

So basically, preliminary parsing/error-checking is done before values and scope and object context are considered. Once that's all done the code can act in concert and be checked for things like whether you're calling a var that hasn't been defined yet. Before that, the new interpreter only sees what's in the eval when it checks for errors. In the case of a that break, what it doesn't see is a loop or a switch surrounding it.

Loop labels are considered during this early parsing/evaluation phase whereas stuff like var existence and function labels appear to be checked later.




回答2:


eval code executes in its own execution context; basically, this means that when the break; executes, it does not know that it's being executed inside a for loop.

If you label the break, it should work:

var myBreak = 'break myLoop;';

myLoop:
  for(var i=0; i < 5; i++) {
    console.log('i is : ' + i);
    eval(myBreak);
  }

console.log('done !');


来源:https://stackoverflow.com/questions/11961963/cant-eval-break-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!