Java Reference
In-Depth Information
The defineProperty() function lets you define a new property with attributes
or change attributes of an existing property. Using the defineProperties() function,
you can do the same but with multiple properties. The getOwnPropertyDescriptor()
function returns the descriptor for the specified property of the object. All three functions
work with the own properties of an object.
The following code defines an origin2D object to define the origin in a 2D
coordinate system and makes both x and y properties nonwritable:
// Define an object
var origin2D = {x:0, y:0};
// Read the property descriptors for x and y
var xDesc = Object.getOwnPropertyDescriptor(origin2D, "x");
var yDesc = Object.getOwnPropertyDescriptor(origin2D, "y");
printf("x.value = %d, x.writable = %b", xDesc.value, xDesc.writable);
printf("y.value = %d, y.writable = %b", yDesc.value, yDesc.writable);
// Make x and y non-writable
Object.defineProperty(origin2D, "x", {writable:false});
Object.defineProperty(origin2D, "y", {writable:false});
print("After setting x and y non-writable... ")
// Read the property descriptors for x and y again
var xDesc = Object.getOwnPropertyDescriptor(origin2D, "x");
var yDesc = Object.getOwnPropertyDescriptor(origin2D, "y");
printf("x.value = %d, x.writable = %b", xDesc.value, xDesc.writable);
printf("y.value = %d, y.writable = %b", yDesc.value, yDesc.writable);
x.value = 0, x.writable = true
y.value = 0, y.writable = true
After setting x and y non-writable...
x.value = 0, x.writable = false
y.value = 0, y.writable = false
The following code shows you how to add a new property using the
Object.defineProperty() function:
// Define an object with no properties
var origin2D = {};
// Add two non-writable x and y properties to origina2D with their
value set to 0.
Object.defineProperty(origin2D, "x", {value:0, writable:false});
Object.defineProperty(origin2D, "y", {value:0, writable:false});
 
Search WWH ::




Custom Search