Java Reference
In-Depth Information
Locking Objects
Object provides several methods that let you lock down objects. These methods give you
finer control as to what parts or features of the object are locked down:
You can prevent extensions of the object (or make it
nonextensible) so new properties cannot be added to it
You can seal the object so that the existing properties cannot be
deleted and new properties cannot be added
You can freeze the object so that the existing properties cannot
be deleted, new properties cannot be added, and properties are
read-only
The Object.preventExtensions(obj) method lets you make the specified object
nonextensible. The Object.seal(obj) method seals the specified object. The Object.
freeze(obj) method freezes the specified object. Notice that once you make an object
nonextensible, sealed, or frozen, there is no way to reverse these properties. You can use
the Object.isExtensible(obj) , Object.isSealed(obj) , and Object.isFrozen(obj)
methods to check if the specified object is extensible, sealed, and frozen, respectively.
In strict mode, an error is thrown if you try to make changes to the object that are not
allowed; for example, adding a new property to a nonextensible object throws an error.
preventing extensions, sealing, and freezing an object affects only that object, not
its prototype. it is still possible to make changes to its prototype and the object will inherit
those changes. if you want to freeze the object completely, you will need to freeze all objects
along the object's prototype chain.
Tip
Listing 4-17 shows how to prevent extensions of an object. It also shows that you
can add a property to the prototype of an otherwise nonextensible object and the object
will inherit that property. The code makes the point object nonextensible and adding a
property named z does not add the property to the object. However, you are able to add
the same property to Object.prototype and the point object inherits it.
Listing 4-17. Preventing Extensions of Objects
// preventextensions.js
var point = {x:1, y:1};
print("isExtensible() = " + Object.isExtensible(point));
// Make point non-extensible
Object.preventExtensions(point);
print("isExtensible() = " + Object.isExtensible(point));
 
 
Search WWH ::




Custom Search