Java ScriptEngine(nashorn& rhino):如何堆叠作用域/绑定? [英] Java ScriptEngine (nashorn & rhino) : how to stack scopes / bindings?

查看:163
本文介绍了Java ScriptEngine(nashorn& rhino):如何堆叠作用域/绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用 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):如何堆叠作用域/绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆