HTML and CSS Reference
In-Depth Information
Listing 8.2 Empowered ES5 properties
TestCase("ES5ObjectTest", {
"test defineProperty": function () {
var circle = {};
Object.defineProperty(circle, "radius", {
value: 4,
writable: false,
configurable: false
assertEquals(4, circle.radius);
The Object.defineProperty method can be used not only to define new
properties on an object, but also to update the descriptor of a property. Updating
a property descriptor only works if the property's configurable attribute is set
to true . Listing 8.3 shows an example of how you can use the existing descriptor
to update only some attributes.
Listing 8.3 Changing a property descriptor
"test changing a property descriptor": function () {
var circle = { radius: 3 };
var descriptor =
Object.getOwnPropertyDescriptor(circle, "radius");
descriptor.configurable = false;
Object.defineProperty(circle, "radius", descriptor);
delete circle.radius;
// Non-configurable radius cannot be deleted
assertEquals(3, circle.radius);
In addition to controlling the property attributes, ES5 also allows con-
trol over the internal [[Extensible]] property of an object. This property con-
trols whether or not properties can be added to the object. Calling Object.
preventExtensions(obj) shuts the object down for further extension and
cannot be undone.
Preventing object extensions and setting property attributes writable and
configurable to false means you can now create immutable objects. This
removes a lot of error checking and complexity brought on by the fact that
Search WWH ::

Custom Search