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
1class Thermostat {
2 constructor(fahrenheit) {
3 this.fahrenheit = fahrenheit;
4 }
5
6 get temperature() {
7 return (5 / 9) * (this.fahrenheit - 32);
8 }
9
10 set temperature(celsius) {
11 this.fahrenheit = (celsius * 9.0) / 5 + 32;
12 }
13}
14
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
1public class Computer
2 {
3 int ram;
4 public int RAM
5 {
6 get
7 {
8 return ram;
9 }
10 set
11 {
12 ram = value; // value is a reserved word and it is a variable that holds the input that is given to ram ( like in the example below )
13 }
14 }
15 }
1const person = {
2 name: "abc",
3
4 get Name() {
5 return this.name;
6 },
7
8 set Name(v) {
9 this.name = v;
10 }
11 };
12
13 console.log(person.Name);
14 person.Name = 'John Doe';
15 console.log(person.Name);