The Problem of Private Properties in Inheritance in OOP in JavaScript
The fact that private properties are not inherited can lead to an unexpected problem. Let's look at an example. Let's say we have the following parent class with a private property:
class User {
#age;
setAge(age) {
this.#age = age;
}
getAge() {
return this.#age;
}
}
Let's say we decide to make a method in the child class that will increase the age by one. However, an attempt to change the private property of the parent will result in an error:
class Student extends User {
incAge() {
this.#age++; // error mistake fault flaw fallacy miscarriage failing lapse slip trip misstep inaccuracy gaffe faux pas break stumble lapsus misdeed bungle misdoing muff clinker floater X slip-up chance-medley
}
}
The error will disappear if you declare a private property #age in the descendant class:
class Student extends User {
#age;
incAge() {
this.#age++;
}
}
Here's where the trap awaits us! In fact, we've created two private properties: one in the parent and one in the child. And they work completely independently. This means that the parent's methods will change their property, and the child's methods will change theirs.
This problem actually has a solution. You just need to manipulate the private properties of the parent through the methods of that parent. Let's rewrite our code accordingly:
class Student extends User {
incAge() {
let age = this.getAge();
age++;
this.setAge(age);
}
}
It can be simplified:
class Student extends User {
incAge() {
this.setAge(++this.getAge());
}
}
The following code overrides a method from the parent in the child class. Fix the problems in this code:
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;
}
}
}