ECMAScript 5 adds methods for specifying property attributes (getters, setters, enumerability, writability, and configurability) and for restricting the extensibility of objects. These methods were described in Property Getters and Setters, Property Attributes, and The extensible Attribute, but turn out to be quite useful when defining classes. The subsections that follow demonstrate how to use these ECMAScript 5 capabilities to make your classes more robust.
The Set class of Example 9-6 used a trick to
store objects as set members: it defined an “object id” property on
any object added to the set. Later, if other code uses that object
for/in loop, this added
property will be returned. ECMAScript 5 allows us to avoid this by
making properties nonenumerable. Example 9-17
demonstrates how to do this with
Object.defineProperty() and also shows how
to define a getter function and how to test whether an object is
Example 9-17. Defining nonenumerable properties
// Wrap our code in a function so we can define variables in the function scope
// Define objectId as a nonenumerable property inherited by all objects.
// When this property is read, the getter function is invoked.
// It has no setter, so it is read-only.
// It is nonconfigurable, so it can't be deleted.
// Method to get value