Chapter 20. Object Property Configuration and Proxies
Accessor Properties: Getters and Setters
There are two types of object properties: data properties and accessor properties. Weâve already seen both, but the accessor properties have been hidden behind some ES6 syntactic sugar (we called them âdynamic propertiesâ in Chapter 9).
Weâre familiar with function properties (or methods); accessor properties are similar except they have two functionsâa getter and a setterâand when accessed, they act more like a data property than a function.
Letâs review dynamic properties. Imagine you have a User
class, with methods setEmail
and getEmail
. We opted to use a âgetâ and âsetâ method instead of just having a property called email
because we want to prevent a user from getting an invalid email address. Our class is very simple (for simplicity, weâll treat any string with an at sign as a valid email address):
const
USER_EMAIL
=
Symbol
();
class
User
{
setEmail
(
value
)
{
if
(
!
/@/
.
test
(
value
))
throw
new
Error(
`invalid email:
${
value
}
`
);
this
[
USER_EMAIL
]
=
value
;
}
getEmail
()
{
return
this
[
USER_EMAIL
];
}
}
In this example, the only thing thatâs compelling us to use two methods (instead of a property) is to prevent the USER_EMAIL
property from receiving an invalid email address. Weâre using a symbol property here to discourage accidental direct access of the property (if we used a string property called email
or even _email
, it would be easy to carelessly access it ...
Get Learning JavaScript, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.