Hi, in my code, I get hold of a function object from some 3rd party Javascript code, and I need to execute that function within a new context, i.e. make new ENGINE_SCOPE bindings available to it. ScriptObjectMirror.call() unfortunately does not allow to define a context to execute in, so I tried to workaround by calling the function from a CompiledScript that in turn can be executed with a custom context:
@Test public void testJsFunctionWithContext() throws ScriptException { ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript"); jdk.nashorn.api.scripting.ScriptObjectMirror jsFunction = (ScriptObjectMirror) engine.eval("function test() {return foo;}"); ScriptContext context = new SimpleScriptContext(); context.setAttribute("foo", "bar", ScriptContext.ENGINE_SCOPE); context.setAttribute("fn", jsFunction, ScriptContext.ENGINE_SCOPE); // does work: access context directly CompiledScript contextWrapper = ((Compilable) engine).compile("foo"); String result = (String) contextWrapper.eval(context); assertEquals("bar", result); // does not work: access context from within function ("foo" is not defined) contextWrapper = ((Compilable) engine).compile("fn()"); result = (String) contextWrapper.eval(context); assertEquals("bar", result); } Is there some mistake I made here, or is it simply not possible for a function object to access variables from a new context? If that’s really not possible, is there maybe a way of turning a function object into a CompiledScript object, which can then be evaluated with a new context? Thanks for any help, Jörg --- Dipl. Inf. Jörg von Frantzius, Technical Director E-Mail joerg.frantz...@aperto.com Phone +49 30 283921-318 Fax +49 30 283921-29 Aperto GmbH – An IBM Company Chausseestraße 5, D-10115 Berlin http://www.aperto.com<http://www.aperto.de/> http://www.facebook.com/aperto https://www.xing.com/companies/apertoag HRB 77049 B, AG Berlin Charlottenburg Geschäftsführer: Dirk Buddensiek, Kai Großmann, Stephan Haagen, Daniel Simon