TL ; DR:
A getter reads a private field. A setter changes it, but only to a value the class allows.
In JavaScript, the keyword get in front of a method makes it the getter. The keyword set in front of a method with the same name makes it the setter. Other code still writes rex.age, as if it were a plain field.
class Dog {
#age;
constructor(age) {
this.#age = age;
}
get age() {
return this.#age;
}
set age(value) {
if (value >= 0) {
this.#age = value;
}
}
}
Full lesson:
In the Access Modifiers lesson, getName() let other code read the private #name. Often other code must change a field too. A setter allows that, and it checks each new value first.
The getter
Write get age() inside the class. Now reading rex.age runs this method, with no parentheses. It returns the private this.#age.
The setter
Write set age(value) next to it. Now rex.age = 4 runs that method, with value set to 4.
The private field and the accessors need different names. Here the field is #age, and both accessors are age.
The rule
A dog's age can't be negative. So the setter changes this.#age only when value is 0 or more. After rex.age = -5, the age stays as it was.
Why not a plain field?
With a plain this.age, any code could set the age to -5. Nothing would check it. The accessors keep the rule inside the class. The code that uses rex.age stays the same.
Your task
The Dog class keeps its age in the private #age. Add a getter age that returns it. Add a setter age that ignores negative values.
The code below the class creates rex, then reads and sets rex.age.
Expected output:
Rex is 3
Rex is still 3
Rex is 4Free plan: 30 tutor messages. Premium is unlimited.
