无法评估中断声明 [英] Can't eval break statement

查看:120
本文介绍了无法评估中断声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码是:

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

触发:

unlabelled break must be inside loop or switch

Firebug中的错误消息代替在控制台中返回完成!吗?

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

是否不可能 eval() break语句?

Is it not possible to eval() break statements ?

谢谢!

编辑:

我现在很困惑。 ^^

I'm getting confused now. ^^


  • 为什么会失败?

  • 当时杰克·万德斯(Jack Wanders)当时是否拥有
    自己的执行上下文?

  • 如果是,为什么他的示例不起作用?

推荐答案

eval在JavaScript解释器的新实例中解析/评估代码。该代码最终将在原始解释器的代码的上下文中执行,但是该代码必须能够在没有外部上下文的情况下执行,因为新实例对它是盲目的。

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.

所以 alert(eval(this.constructor.name))将为您提供正确的对象上下文名称(全局窗口)。

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.

在此早期的解析/评估阶段,将考虑使用循环标签,而诸如var存在和功能标签之类的东西似乎稍后会被检查。

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

这篇关于无法评估中断声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆