Once you know how to create an object, you may wish to learn about object property descriptors. As a recap, let us say you have an object –cat:
Each object property contains more information than just a value. For example, you can print other property information using the Object.getOwnPropertyDescriptor method
On the console, you can see that a property name offers further information:
As of now, you know about object property descriptors, so if you are required to make a property Read-Only, you will set the property writable to false.
- Prevent an object from having new property
- In addition to requirement 1, mark all properties configurable to false
- In addition to requirement 2, make all properties writable to false
Starting with ECMA 6, you have methods to achieve the above requirements. Let us take them one by one:
Let us say, you have an object – cat:
To prevent the default behavior from adding properties dynamically in an object, you need to use Object.preventExtensions(). This method prevents an object from having new properties added to it.
In strict mode, you will get an error with very clear messaging that states, “cannot add property, object is not extensible”
To summarize, you should use the object.preventExtensions method to prevent an object from having new properties added to it.