Java Reference
In-Depth Information
You will not use the eval() function for such a trivial computation. Nashorn can
execute an arithmetic expression like 100 + 200 without using the eval() function. You
will use it when you get Nashorn code as a string at runtime.
The eval() function is executed in the context of the caller. If it is called from the
global context, it executes in the global context. If it is called from a function, it executes
in the context of the function.
Listing 4-20 demonstrates the context of the eval() function execution. The first
time, it is called in the global context, so it defined a new variable z and sets it to 300 in
the global context. It reads the value of x from the global context, multiplies it with 2, and
returns 200 that is set to y . The second time, it is called from the function and it works on
local variables x , y , and x of the function.
Listing 4-20. The Contents of the EvalTest.js File
// EvalTest.js
var x = 100;
var y = eval("var z = 300; x * 2;"); // Called from the global context
print(x, y, z);
function testEval() {
var x = 300;
// Called from the function context
var y = eval("var z = 900; x * 2;");
print(x, y, z);
}
testEval();
100 200 300
300 600 900
Variable Scoping and Hoisting
Java supports block-level scoping. A variable declared in a block is local to that
block and it is not accessible before and after the block. Nashorn (and all JavaScript
implementations) support two scopes:
Global Scope
Function Scope
Variable and function declarations in the global code are available everywhere in
the global scope. Similarly, variable and function declarations in a function are available
everywhere inside the function.
 
Search WWH ::




Custom Search