HTML and CSS Reference
In-Depth Information
ES3 objects are basically mutable collections of properties. The Object.seal
method can be used to seal an entire object; all of the object's own properties
will have their configurable attribute set to false , and subsequently the
object's [[Extensible]] property is set to false . Using a browser that supports
Object.getOwnPropertyDescriptor and Object.defineProperty ,
the seal method could be implemented as in Listing 8.4.
Listing 8.4 Possible Object.seal implementation
if (!Object.seal && Object.getOwnPropertyNames &&
Object.getOwnPropertyDescriptor &&
Object.defineProperty && Object.preventExtensions) {
Object.seal = function (object) {
var properties = Object.getOwnPropertyNames(object);
var desc, prop;
for(vari=0,l=properties.length; i < l; i++) {
prop = properties[i];
desc = Object.getOwnPropertyDescriptor(object, prop);
if (desc.configurable) {
desc.configurable = false;
Object.defineProperty(object, prop, desc);
return object;
We can check whether or not an object is sealed using Object.isSealed .
Notice how this example also uses Object.getOwnPropertyNames , which
returns the names of all the object's own properties, including those whose
enumerable attribute is false . The similar method Object.keys returns the
property names of all enumerable properties of an object, exactly like the method
in Prototype.js does today.
To easily make an entire object immutable, we can use the related, but even more
restrictive function Object.freeze . freeze works like seal , and additionally
sets all the properties writable attributes to false, thus completely locking the
object down for modification.
Search WWH ::

Custom Search