Java Reference
In-Depth Information
The program performs the following steps:
Creates a Nashorn engine with default options.
Executes a script using the
eval() method that uses the default
script context of the engine. The script creates a global variable
named msg that is stored in the script globals. You can refer to
the variable using its simple name msg or this.msg in the global
scope.
eval() method that uses the default
script context of the engine that prints the value of the msg
variable. The first line in the output confirms that the correct
value of the msg variable is printed.
Executes a script using the
eval() method that uses a new script
context. The script tries to print the value of the global variable
msg . The second line in the output, by printing undefined ,
confirms that the variable named msg does not exist in the script
globals.
Executes a script using the
This is the default behavior of the Nashorn engine. It creates a fresh copy of the
globals per script context. If you want to use the globals of the default context (if you want
to share globals), you can do so by copying the engine scope Bindings of the default
context to your new script context. Listing 12-2 uses this approach to share the script
globals between two script contexts.
Listing 12-2. Sharing Script Globals by Copying the Engine Scope Bindings of the
Engine's Default Context
// CopyingGlobals.java
package com.jdojo.script;
import javax.script.Bindings;
import javax.script.ScriptContext;
import static javax.script.ScriptContext.ENGINE_SCOPE;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleScriptContext;
public class CopyingGlobals {
public static void main(String[] args) {
// Get the Nashorn script engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
Search WWH ::




Custom Search