Java Reference
In-Depth Information
Are you surprised by the output? Accessing a nonexisting property of an object in
Nashorn does not generate an error. If you read a nonexisting property, undefined is
returned; if you set a nonexisting property, a new property with the same name is created
with the new value. The following code shows this behavior:
// Create an object with one property x
var point3D = {x:10};
// Create a new property named y and assign -20 to it
point3D.y = -20;
// Create a new property named z and assign 35 to it
point3D.z = 35;
// Print all properties of point3D
print("x = " + point3D.x + ", y =" + point3D.y + ", z = " + point3D.z);
x = 10, y =-20, z = 35
How do you know the difference between a nonexisting property and an existing
property with the value undefined ? You can use the in operator to know whether a
property exists in an object. The syntax is:
propertyNameExpression in objectExpression
The propertyNameExpression evaluates to a string that is the name of the property.
The objectExpression evaluates to an object. The in operator returns true if the object
has a property with the specified name; otherwise, it returns false . The in operator
searches own as well as inherited properties of the object. The following code shows how
to use the in operator:
// Create an object with x and y properties
var colorPoint2D = {x:10, y:20};
// Check if the object has a property named x
var xExists = "x" in colorPoint2D;
print("Property x exists: " + xExists + ", x = " + colorPoint2D.x);
// Check if the object has a property named color
var colorExists = "color" in colorPoint2D;
print("Property color exists: " + colorExists + ", color = " +
colorPoint2D.color);
 
Search WWH ::




Custom Search