Java Reference
In-Depth Information
Using Strict Mode
You can use the strict mode in Nashorn script by using the "use strict" directive. It is
used in the beginning of the global code or the beginning of the function code. If it is used
in the beginning of the global code, all code is considered executing in string mode. If it
occurs in the beginning of the function code, only that function code executes in the strict
mode. You can also use the "use strict" directive in the script executed by the eval()
function.
The following snippet of code uses the "use strict" directive for the global scope:
"use strict";
// An error. Using a variable without declaring it with var
x = 10;
// other code goes here
The following code will throw an error when the test() function is called because
the function uses the "use strict" directive and it uses a variable named y without
declaring it with the keyword var :
x = 10; // OK. The global code is not in strict mode
function test() {
"use strict";
y = 100; // Will cause an error when executed
}
test();
Built-in Global Objects
Nashorn defines many built-in objects. I will discuss some of them in the subsequent
sections.
The Object Object
Nashorn provides a built-in object called Object . You can think of it similar to the
java.lang.Object class in Java. Object in Nashorn serves as the base object for other
objects. It has several useful properties that are used to work with all types of objects.
I have already discussed many of them in previous sections.
Object is a function that can also be used as a constructor. It accepts an optional
parameter. If you call the Object function, it has the same effect of calling the Object
constructor with the new operator. If you pass an object to the function, it returns the
reference of the same object. If you pass a primitive value, it returns a wrapper object that
 
Search WWH ::




Custom Search