我有两个js文件,
- 一个是js库
- 第二个是一个简单的脚本,通常大约 50 行,需要访问库中的函数。
在我的项目中,我试图在我的应用程序启动期间预编译所有 javascript,然后在运行时只调用具有所需参数的 CompiledScripts。
我最终得到了以下代码
static String LIBRARY = "function hello(arg) {return 'Hello ' + arg;};";
static String SCRIPT = "hello(arg)";
public static void main(String... args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
Compilable compilable = ((Compilable) engine);
CompiledScript compiledLib = compilable.compile(LIBRARY);
compiledLib.eval();
CompiledScript actualScript = compilable.compile(SCRIPT);
Bindings helloParams = new SimpleBindings();
helloParams.put("arg","world");
ScriptObjectMirror result = (ScriptObjectMirror) actualScript.eval(helloParams);
System.out.println(result);
}
但是这段代码会抛出一个错误
> compiledScript.eval(helloParams);
<eval>:1 ReferenceError: "hello" is not defined
如何从“actualScript”中访问“compiledLib”(即方法和变量)的上下文?