Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

=== returns false in Nashorn when both references should be pointing to the same object

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.

like image 371
Vivin Paliath Avatar asked Dec 21 '15 22:12

Vivin Paliath


People also ask

Does === return false?

Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!

Which is the new command line tool for the nashorn JavaScript engine in Java 8?

jjs. For Nashorn engine, JAVA 8 introduces a new command line tool, jjs, to execute javascript codes at console.

Can we run JavaScript on JVM?

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.


1 Answers

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

like image 120
A. Sundararajan Avatar answered Sep 17 '22 20:09

A. Sundararajan