Java Reference
In-Depth Information
Defining a constant in Nashorn is not straightforward. You will need to use the
Object.defineProperty()
function to define a constant. The following code defines
a constant named
MAX_SIZE
in the global scope. The keyword
this
refers to the global
object in the following code:
// Define a constant named MAX_SIZE with a value 100
Object.defineProperty(this, "MAX_SIZE", {value:100, writable:false,
configurable:false});
printf("MAX_SIZE = %d", MAX_SIZE);
MAX_SIZE = 100
You can iterate over
enumerable
properties of an object using the
for..in
and
for..
each..in
iterator statements. The following code creates an object with two properties
that are
enumerable
by default, uses the
for..in
and
for..each..in
statements to iterate
over the properties, changes one of the properties to nonenumerable, and iterates over
the properties again:
// Create an object with two properties x and y
var point = {x:10, y:20};
// Using for..in reports x and y as properties
for(var prop in point) {
printf("point[%s] = %d", prop, point[prop]);
}
// Make x non-enumerable
Object.defineProperty(point, "x", {enumerable: false});
print("After making x non-enumerable");
// Using for..in reports only y as property
// because x is now non-enumerable
for(var prop in point) {
printf("point[%s] = %d", prop, point[prop]);
}
point[x] = 10
point[y] = 20
After making x non-enumerable
point[y] = 20
Search WWH ::
Custom Search