javascript - 在 try/catch 中评估 Rhino 中的错误

标签 javascript eval rhino

好的,我想我在 Rhino 中发现了一个错误。我正在尝试在全局范围内动态评估代码,如果我只执行 eval.call(null, "code to eval"); 它工作正常一切都很好,直到我 try catch 异常。当我用 try/catch 包围该代码时,该代码实际上并未在全局上下文中求值。

为了说明错误:

function works(str) {
  eval.call(null, str);
}

function doesntWork(str, count) {
  try {
    eval.call(null, str);
  } catch (e) {
    println('Error in ' + count + ' call: ' + e);
  }
}

works('var abc = 123;');
works('println("The value: " + abc);');
doesntWork('var xyz = 123;', 'first');
doesntWork('println("The value: " + xyz);', 'second');

当我在 OpenJDK 6 内置的 Rhino 中运行它时,我得到:

The value: 123
Error in second call: ReferenceError: "xyz" is not defined.

当我将 println 更改为 console.log 并在 Chrome 中运行它时,我更加确信这是一个错误,此时我得到了 2 个“值:123”日志,这与我预期的一样。

此外,我查找了 ECMAScript standard得到这个:

10.4.2 Entering Eval Code

The following steps are performed when control enters the execution context for eval code:

  1. If there is no calling context or if the eval code is not being evaluated by a direct call (15.1.2.1.1) to the eval function then,
    1. Initialize the execution context as if it was a global execution context using the eval code as C as described in 10.4.1.1.
  2. Else,
    1. Set the ThisBinding to the same value as the ThisBinding of the calling execution context.
    2. Set the LexicalEnvironment to the same value as the LexicalEnvironment of the calling execution context.
    3. Set the VariableEnvironment to the same value as the VariableEnvironment of the calling execution context.
  3. If the eval code is strict code, then
    1. Let strictVarEnv be the result of calling NewDeclarativeEnvironment passing the LexicalEnvironment as the argument.
    2. Set the LexicalEnvironment to strictVarEnv.
    3. Set the VariableEnvironment to strictVarEnv.
  4. Perform Declaration Binding Instantiation as described in 10.5 using the eval code.

第一点是我的情况,或者“没有调用上下文”,所以这应该在全局上下文中进行评估,我的 xyz 变量应该可以正常工作。

我真的遇到了 Rhino 错误,还是我遗漏了什么?

最佳答案

内置于 JDK 中的 Rhino 代码非常非常古老,并且它有很多错误已在 Mozilla 的当前版本软件中修复(很长时间)。

如果您正在开始一个新项目,我强烈建议您研究仅使用来自 Mozilla 的代码来集成 Rhino 是什么感觉,并且相信 1.6 中的所有“ScriptEngine”东西都不是那里(或者,可能,围绕 Mozilla 的东西实现你自己的 ScriptEngine 代码)。不要重蹈我的覆辙。两次。 :-(

关于javascript - 在 try/catch 中评估 Rhino 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6233422/

相关文章:

javascript - 是否可以缩小 ejs 文件中的 JS 代码?

python - 有/没有事先编译的 exec 语句

java - 如何将 Rhino Javascript 1.7 库添加到 Weblogic 10 中的类路径

javascript - nodejs/V8 是否将编译后的机器代码存储在磁盘上的任何位置?

javascript - WCF 服务在 GoDaddy 上无法运行,如何调试?

javascript - uglify-js 支持 es6 及以上版本吗?

javascript - 带有 eval 的函数无法通过缩小

javascript - 每当定义 var 时运行函数

java - 犀牛打印功能

javascript - Rhino 不枚举 'arguments' 到一个函数