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 ?
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 customBindings
implementation which can fall back to the parentBindings
.Edit: under Nashorn only (not Rhino, sorry), I think
jdk.nashorn.api.scripting.ScriptObjectMirror
may be more capable, since it hassetProto()
to change the prototype object. More aboutScriptObjectMirror
here: https://wiki.openjdk.java.net/display/Nashorn/Nashorn+jsr223+engine+notes