Java Reference
In-Depth Information
In this code, you could have used the
defineProperties()
function to define both
x
and
y
properties in one shot. Both functions
defineProperty()
and
defineProperties()
return the object on which the property or properties are being set so that you can chain
their calls. The following code rewrites the previous example:
// Create an empty object
var origin2D = {};
// Add two non-writable x and y properties to origina2D
// with their value set to 0.
Object.defineProperties(origin2D, {x: {value:0, writable: false},
y: {value:0, writable: false}});
■
When you add a property to an object in the object literal or by assigning a value
to the property, the default values for
writable
,
enumerable
, and
configurable
properties
are set to
true
. When you use a property descriptor to define a property or alter the property's
attributes, the default values for these attributes in the property descriptor is
false
.
Make sure you specify values for all attributes that needs to be set to
true
when using
a property descriptor.
Tip
Once you set the
writable
attribute of a property to
false
, changing its value has no
effect. In strict mode, changing the value of a nonwritable property generates an error:
var point = {x:0, y:10};
printf("x = %d", point.x);
// Make x non-writable
Object.defineProperty(point, "x", {writable: false});
// Try changing the value of x
point.x = 100; // Has no effect, because x is non-writable
printf("x = %d", point.x);
x = 0
x = 0
Search WWH ::
Custom Search