@seangarvey/

personWithGettersAndSetters

JavaScript

Created an object to represent a person with a name and age. For both the name and age, included setters and getters (for the first time).

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
let person = {
  _name: 'Lu Xun',
  _age: 137,
  _both() {
    return `${this._name} is currently ${this._age} years old.`;
  },
  
  get both() {
    return this._both;
  },
  
  set age(ageIn) {
    if (typeof ageIn === 'number') {
      let originalAge = this._age;
      this._age = ageIn;
      console.log(`Age changed from ${originalAge} to ${this._age}.`);
    }
    else {
      console.log(`${ageIn} is invalid for the age's key-value. Change ${ageIn} to/into a Number.`);
      return 'Invalid Input.';
    }
  },
  
  get age() {
    // return `Age is currently ${this._age} years old.`;
    return this._age;
  },
  
  set name(nameIn) {
    if (typeof nameIn === 'string') {
            let defaultName = this._name;
            this._name = nameIn;
            console.log(`The name's key-value was changed from ${defaultName} to ${this._name}.`);
          } else {
            console.log(`Change ${nameIn} to/into a(ny) String for the name's key-value.`);
            return 'Invalid Input.';
        }
  },
  
  get name() {
    // return `Name is ${this._name}.`;
    return this._name;
  }
};
// Using dot notation (but could have used bracket notation if desired) to modify object properties.
person.age = 28;
person.name = 28; // oops, correct on next line.
// Thoroughout the program I use single-quotes (Best Practice). Yet, double-quotes are equivalent.
// Assigning the name (property) the value, 'Sean', is equivalent to the value "Sean", for instance.
// person.name = "Sean";
person.name = 'Twenty Eight'
person.name = 'Sean';
person.name = 'Random';
person.name = 'Sean';

// Log to the console name, age, and then both in one statement.
console.log(`The person's name is ${person.name}.`);
console.log(`The person's age is now ${person.age} years old.`);
console.log(person.both());
Native Browser JavaScript