Here's an example that demonstrates the problem I am facing:
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
new String[] { "-strict" }
);
try {
engine.eval("function Foo(src) { this.src = src }; var e = { x: new Foo(\"what\") };");
ScriptContext c = new SimpleScriptContext();
c.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
c.getBindings(ScriptContext.ENGINE_SCOPE).putAll(engine.getBindings(ScriptContext.ENGINE_SCOPE));
System.out.println(engine.eval("var z = e.x; z === e.x;", c));
} catch(Exception e) {
throw new RuntimeException(e);
}
I'm aware that objects that were instantiated in another context, are considered "foreign" and end up being wrapped by a ScriptObjectMirror
instance. I am assuming this is why I'm running into a problem here. I believe whenever x
is dereferenced, a new ScriptObjectMirror
instance is created; that's the only thing that can explain the following bit of code also returning false
:
System.out.println(engine.eval("e.x === e.x;", c));
Is there a way around this? I'm looking for something I can do from Java to maybe set up up contexts/bindings a certain way instead of having to write code in JavaScript to get around this.
Just for the benefit of others who may be reading this question here:
There is a discussion thread on this in nashorn-dev openjdk email alias: http://mail.openjdk.java.net/pipermail/nashorn-dev/2015-December/005764.html