Protected Properties in OOP in JavaScript
Let's also introduce protected properties. Let's also start their names with an underscore. Let's look at an example. Let's make a parent class with a protected property containing age:
class User {
setAge(age) {
this._age = age;
}
getAge() {
return this._age;
}
}
In the descendant class we will create a method that increases the age by one:
class Student extends User {
incAge() {
this._age++;
}
}
Rewrite the following code using a protected property:
class User {
#name;
setName(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
class Employee extends User {
setName(name) {
if (name.length > 0) {
this.#name = name;
}
}
}