2

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 ?

Nicolas Albert
  • 2,566
  • 1
  • 12
  • 16

1 Answers1

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

seanf
  • 5,856
  • 2
  • 40
  • 51
  • The API is not sufficient. It is not known if a value assignment to a variable is global or local (with or without the "var" keyword for his statement). – Nicolas Albert Mar 06 '15 at 16:08