Read Only Properties in ES5
July 29th, 2010 by James CarrI thought I’d take a quick moment to provide some examples of making object properties read only in EcmaScript 5 (and by extension node.js). There’s several ways to accomplish it, so I’ll just iterate over all the different ways.
Object.freeze
The quickest way to make all properties of an object read only is by calling Object.freeze on it. The interesting thing here is that (at least in node.js) no exception or warning will take place if you try to assign a read only property… it will appear that the assignment succeeded when in reality it didn’t.
Let’s try an object with some additional types… nested object and an array.
In this example, we see that the array and object represented by b can in fact be modified, they just can’t be reassigned to something new. It really just locks the reference. However if we loop over each property and freeze each one each will be unmodifiable and the attempt to push an element onto the array with throw an exception stating TypeError: Can't add property 4, object is not extensible.
Define Only a Getter
Another way to make a property read only is by only defining a getter for it. You can do this both via defineProperty or defineGetter
Both will throw an exception on an attempt to reassign them.
Defined as Not Writable Via Property Descriptor
One more way is to define the writable attribute in the property descriptor.
That’s just a quick overview, there’s also quite a few interesting tricks to locking object instances.