Java Reference
In-Depth Information
Strict and Nonstrict Modes
Nashorn can operate in two modes: strict and nonstrict. Some features of ECMAScript
cannot be used in strict mode. Typically, features that are error-prone are not allowed
in strict mode. Some features that work in nonstrict mode will generate an error in
strict mode. I will list the features that are applicable to strict mode while explaining the
specific features. You can enable strict mode in your scripts in two ways:
-strict option with the jjs command
Using the
"use strict" or 'use strict' directive
The following command invokes the jjs command-line tool in strict mode and
attempts to assign a value of 10 to a variable named empId without declaring the variable.
You receive an error that says that the variable empId is not defined:
Using the
C:\> jjs -strict
jjs> empId = 10;
<shell>:1 ReferenceError: "empId" is not defined
jjs> exit()
The solution is to use the keyword var (discussed shortly) to declare the empId
variable in strict mode.
The following command invokes the jjs command-line tool in nonstrict mode
(without the -strict option) and attempts to assign a value of 10 to a variable named
empId without declaring the variable. This time, you do not receive an error; rather, the
value of the variable (that is, 10 ) is printed:
C:\> jjs
jjs> empId = 10;
10
jjs>exit()
Listing 4-1 shows a script using the use strict directive. The directive is specified in
the beginning of the script or functions. The use strict directive is simply the string "use
strict" . You can also enclose the directive in single quotes like 'use strict' . The script
assigns a value to a variable without declaring the variable, which will generate an error
because strict mode is enabled.
Listing 4-1. A Script with the Strict Mode Directive
// strict.js
"use strict"; // This is the use strict directive.
empId = 10; // This will generate an error.
 
Search WWH ::




Custom Search