Accessor Properties in OOP in JavaScript
There are two types of object properties.
The first type is data properties (data properties). We already know how to work with them. All the properties we've used so far have been data properties.
The second type of properties we haven't looked at yet are accessor properties (accessor properties). These are essentially functions that are used to assign and get a value, but in external code they look like regular object properties.
Accessor properties are created using the get and set keywords written when declaring methods:
class User {
get name() {
}
set name(name) {
}
}
As a result of such a declaration, our class will have the property name. At the same time, when trying to read this property, the method declared via get will be called:
let name = user.name;
When attempting to write, the method declared via set will be called:
user.name = 'john';
The following class is given:
class Employee {
get name() {
console.log('get');
}
set name(name) {
console.log('set');
}
}
Create an object of this class and try to write and read data from the name property.