Property descriptors define property behaviour. They are attributes of the property.
Everything is an object in Javascript. Yes, I know - except those pesky things called primitives on which objects are built. We saw some (quick discussions on objects and properties)[/objects-and-props-in-javascript/] before - but I wanted to outline the descriptors further.
You can see it yourself using a simple statement.
|
|
This is telling me what I could potentially do with color
property other than seeing the value
.
Following are the available property descriptors:
- value
- writable
- enumerable
- configurable
- get
- set
You can read attributes of the property (like what we have done above ) or set property attributes of an object by yourself.
|
|
The above example will throw an error if use strict
mode is enabled. Else it fails silently. Note that only size
is read-only, but you can add further attributes to the size. For e.g. apple.size.price=2
Btw, you do remember that we have to use Object.freeze()
if you want to make all properties read-only, right? It can be used against specific properties as well. So the below is valid.
|
|
You can also define new properties for any object and set its descriptors to your heart content.
Similarly you can use enumerate
to define enumerable, or iterable property. configurable
prevents certain properties from being changed or property being deleted.
Along with the properties outlined above, we also have get
/set
functions which are called when properties are being read or written respectively.
|
|
get
/set
enable you to customize logic to fetch or write values to the specific property of the object.