Accessors: Getters and Setters
This is part 1 of a brief introduction to getters and setters in JavaScript. Getters and Setters are ES5 features. Objects have two types of properties:
- Static data property
- Accessor property
So far we have come across static data properties in the objects that we have been making. For example:
let blackLivesMatter = { status: true, usecase: 'daily' }
In this object, status and usecase properties are static. So what then are accessor
properties? Accessor properties are functions that will execute on either getting or setting a value.
The two types of accessor properties are:
Getter property: Upon getting a property of an object such as car.color the value of the
property will be generated implicitly by calling a function. The getter works upon reading a
property.
Setter property: When a property is set for example on an object car.color = ‘red’
a function is executed implicitly passing the value of a property, in this case ‘red’ as an
argument to the function. The return value of the function is set to the property. The setter works upon assignment of a property
Leave a Reply