Java ScriptEngine (nashorn & rhino) : how to stack scopes / bindings?

放肆的年华 提交于 2020-01-04 17:54:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!