I am confused as to what the point of getters and setters are in ECMAScript 6 classes. What is the purpose? Below is an example I am referring to:
class Empl
class Employee {
constructor(name) {
this._name = name;
}
doWork() {
return `${this._name} is working`;
}
get name() {
// when you get this by employeeInstance.mame
// the code below will be triggered
// and you can do some logic here
// just like `console.log` something you want
console.log('get triggered!')
return this._name.toUpperCase();
}
set name(newName) {
// the same as `get`
// when you employeeInstance.mame = 'xxx'
// the code blew will be trigged
// and you can also do some logic
// like here is a `console.log` and `if check`
console.log('set triggered!')
if (newName) {
this._name = newName;
}
}
}
const employeeInstance = new Employee('mike')
employeeInstance.name
employeeInstance.name = '' // this won't be success, because the `if check`
console.log(employeeInstance.name)
// =>
// get triggered
// set triggered
// get triggered
// MIKE
Anyway the getter and setter is just like a spy. It spies the property of an object, so that you can do something, every time you get or set the value of the property.