What are getters and setters for in ECMAScript 6 classes?
These setter and getter allow you to use the properties directly (without using the parenthesis)
var emp = new Employee("TruMan1");
if (emp.name) {
// uses the get method in the background
}
emp.name = "New name"; // uses the setter in the background
This is only to set and get the value of the property.
Getters and setters in ES6 serve the same purpose that they do in other languages... including ES5. ES5 already allows getters and setters via Object.defineProperty
, though they're less clean and more cumbersome to use.
Effectively, getters and setters allow you to use standard property access notation for reads and writes while still having the ability to customize how the property is retrieved and mutated without needed explicit getter and setter methods.
In the Employee class above, this would mean you could access the name
property like this:
console.log(someEmployee.name);
It would look like a normal property access, but it would actually call toUpperCase
on the name before returning it. Similarly, doing this:
someEmployee.name = null;
would access the setter, and it would not modify the internal _name
property because of the guard clause introduced in name
's setter.
See also the general question Why use getters and setters? for more information about why being able to modify the functionality of member access is useful.