js why to use getters and setters 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: javascript getters and setters
class Book {
constructor(author) {
this._author = author;
}
get writer() {
return this._author;
}
set writer(updatedAuthor) {
this._author = updatedAuthor;
}
}
const novel = new Book('anonymous');
console.log(novel.writer);
novel.writer = 'newAuthor';
console.log(novel.writer);
Example 3: 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.