By default if we try to assign value or access value of a object property the get and set methods are automatically called respectively. But sometimes if we want to extend the functionality of object we can define our get and set methods. Here’s how its done:
ES6 implementation
Lets assume we have a simple Name class:
In this example we are have 3 properties defined:
- first
- last
- fullname (defined with custom get and set)
We define the get method property fullname with get
in front of property name and same with set. With the help of our custom set we are defining our first and last property by making it uppercase and splitting the string. This way we can adapt our properties to be more flexible like adding validation checks, calling other functions, setting other properties,etc and handle the values in any way we want and extend the functionality.
Object.definedProperty implementation
We can use Object.definedProperty
to define properties inside the constructor to specify custom get
and set
for our property.