- Data properties
- Accessor properties
The first kind is data properties. We already know how to work with them. All properties that we’ve been using until now were data properties.
get- to define a getter method to get the property value
set- to define a setter method to set the property value
Getters and Setters:
The getter works when
obj.propName is read, the setter – when it is assigned.
We don’t call
user.fullName as a function, we read it normally: the getter runs behind the scenes.
As of now,
fullName has only a getter. If we attempt to assign
user.fullName=, there will be an error:
Let’s fix it by adding a setter for
Why Using Getters and Setters?
- It gives simpler syntax
- It allows equal syntax for properties and methods
- It can secure better data quality
- It is useful for doing things behind-the-scenes