问题描述
我必须使用 Rhino1.7R4 及其 org.mozilla.javascript 软件包来移植软件,才能使用 javax.script 软件包和其ScriptEngine(Java 6中的 Rhino 和Java 8中的 Nashorn ).
I have to port a software using Rhino1.7R4 and its org.mozilla.javascript package to use the javax.script package and its ScriptEngine (Rhino in Java 6 & 7, Nashorn in Java 8).
主要问题是堆栈作用域(绑定).我使用Rhino罐子来做:
The main problem is to stack scopes (Bindings).Using the Rhino jar, I do:
Scriptable scope ...
Scriptable newScope = javascriptContext.initStandardObjects();
newScope.setParentScope(scope);
所以
- 如果定义的变量不带var,则为全局变量(根作用域)
- 如果变量是用var定义的,则它是局部变量(当前作用域)
- 如果访问或修改了变量,请在其当前作用域,父级,祖父级...以及全局范围内查找引擎
这是JS的标准行为.
如何使用javax.script API与 setParentScope 相同?
How can I do the same as setParentScope with javax.script API ?
推荐答案
在我的JDK中找不到的javax.script.Bindings
实现中没有任何一种递归查找.我认为您唯一的选择是编写一个自定义Bindings
实现,该实现可以回退到父Bindings
.
None of the javax.script.Bindings
implementations I can find in my JDK has any sort of recursive lookup. I think your only option would be to write a custom Bindings
implementation which can fall back to the parent Bindings
.
仅在Nashorn下(不是Rhino,抱歉),我认为jdk.nashorn.api.scripting.ScriptObjectMirror
可能更强大,因为它具有setProto()
可以更改原型对象.有关ScriptObjectMirror
的更多信息,请参见: https://wiki.openjdk. java.net/display/Nashorn/Nashorn+jsr223+engine+notes
under Nashorn only (not Rhino, sorry), I think jdk.nashorn.api.scripting.ScriptObjectMirror
may be more capable, since it has setProto()
to change the prototype object. More about ScriptObjectMirror
here: https://wiki.openjdk.java.net/display/Nashorn/Nashorn+jsr223+engine+notes
这篇关于Java ScriptEngine(nashorn& rhino):如何堆叠作用域/绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!