javascript setters & getters code example
Example 1: getters and setters javascript classes
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name.toUpperCase();
}
set name(newName) {
this._name = newName;
}
walk() {
console.log(this._name + ' is walking.');
}
}
let bob = new Person('Bob');
console.log(bob.name);
Example 2: js why to use getters and setters
1) Syntax reasons. It’s easier and faster to read code
created with accessor functions
2) Encapsulation. I can create safer code with accessor functions.