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.
Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!
jjs. For Nashorn engine, JAVA 8 introduces a new command line tool, jjs, to execute javascript codes at console.
Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual Machine). Java provides a command-line tool jjs which is used to execute JavaScript code. You can execute JavaScript code by using jjs command-line tool and by embedding into Java source code.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With