1// *** JS Class GETTER / SETTER (+split)
2
3 class Person {
4 constructor(firstname, lastname) {
5 this.firstname = firstname;
6 this.lastname = lastname;
7 }
8 // getters => access properties
9 // setters => change or mutate them
10 get fullName() {
11 return `Hello ${this.firstname} ${this.lastname}`;
12 }
13 set fullName(space) {
14 const parts = space.split(' ');
15 this.firstname = parts[0];
16 this.lastname = parts[1];
17 }
18 }
19 let run = document.getElementById("run");
20 run.addEventListener('click', () => {
21 let john = new Person('John', 'Connor');
22 console.log(john.fullName);
23 john.fullName = 'Billy Butcher';
24 console.log(john.firstname + ' ' + john.lastname);
25 //console.log(`${john.firstname} ${john.lastname}`); same output
26 // => has to be john.firstname otherwise undefined
27 })
28// output => Hello John Connor | Billy Butcher
1let obj = {
2 log: ['a', 'b', 'c'],
3 get latest() {
4 if (this.log.length === 0) {
5 return undefined;
6 }
7 return this.log[this.log.length - 1];
8 }
9};
10
11obj.log.push('d');
12console.log(obj.latest); //output: 'd'
1/*Getter functions are meant to simply return (get) the value of an object's
2private variable to the user without the user directly accessing the private
3variable.*/
4/*Setter functions are meant to modify (set) the value of an object's private
5variable based on the value passed into the setter function. This change could
6involve calculations, or even overwriting the previous value completely.*/
7class Book {
8 constructor(author) {
9 this._author = author;
10 }
11 // getter
12 get writer() {
13 return this._author;
14 }
15 // setter
16 set writer(updatedAuthor) {
17 this._author = updatedAuthor;
18 }
19}
20const novel = new Book('anonymous');
21console.log(novel.writer); // anonymous
22novel.writer = 'newAuthor';
23console.log(novel.writer); // newAuthor
1// ES6 get and set
2class Person {
3 constructor(name) {
4 this._name = name;
5 }
6
7 get name() {
8 return this._name.toUpperCase();
9 }
10
11 set name(newName) {
12 this._name = newName; // validation could be checked here such as only allowing non numerical values
13 }
14
15 walk() {
16 console.log(this._name + ' is walking.');
17 }
18}
19
20let bob = new Person('Bob');
21console.log(bob.name); // Outputs 'BOB'
11) Syntax reasons. It’s easier and faster to read code
2created with accessor functions
32) Encapsulation. I can create safer code with accessor functions.