Java Reference
In-Depth Information
The with Statement
Nashorn executes a script in a context called execution context. It looks up an unqualified
name in the script using the scope chain associated with the execution context. The name
is searched in the closest scope first. If it is not found, the search continues up the scope
chain until the name is found or the search is performed at the top of the scope chain. Its
syntax is:
with(expression)
statement
The with statement adds the specified expression that evaluates to an object to the
head of the scope chain while executing the statement .
the use of the with statement is deprecated because it leads to the confusion
as to where the unqualified name exists—in the object specified in the with statement or
somewhere up the scope chain. it is not allowed in strict mode.
Tip
The following code demonstrates the use of the with statement:
var greetings = new String("Hello");
// Must use greetings.length to access the length property
// of the String object named greetings
printf("greetings = %s, length = %d", greetings, greetings.length);
with(greetings) {
// You can use the length property of the greetings object
// as an unqualified identifier within this with statement.
printf("greetings = %s, length = %d", greetings, length);
}
with(new String("Hi")) {
// The toString() and length will be resolved using the
// new String("Hi") object
printf("greetings = %s, length = %d", toString(), length);
}
with(Math) {
// Compute the area of a circle
var radius = 2.3;
// PI and pow are resolved as properties of the Math object
var area = PI * pow(radius, 2);
printf("Radius = %.2f, Area = %.2f", radius, area);
}
 
 
Search WWH ::




Custom Search