问题
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).
The main problem is to stack scopes (Bindings). Using the Rhino jar, I do:
Scriptable scope ...
Scriptable newScope = javascriptContext.initStandardObjects();
newScope.setParentScope(scope);
So
- if a variable is defined without var, it's a global variable (root scope)
- if a variable is defined with var, it's a local variable (current scope)
- if a variable is accessed or modified, engine lookup in its current scope, and parent, and grand parent ... and the global scope
This is the JS standard behavior.
How can I do the same as setParentScope with javax.script API ?
回答1:
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
.
Edit: 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
来源:https://stackoverflow.com/questions/28212121/java-scriptengine-nashorn-rhino-how-to-stack-scopes-bindings