Protected Methods in OOP in JavaScript
Private methods are not inherited and are not visible outside the class. Sometimes, however, you need methods that are inherited but not visible outside the class. Such methods are called protected (protected). JavaScript, unfortunately, does not support such methods.
So I propose to introduce some convention that allows creating such methods. We will start the names of such methods with an underscore. In fact, we use the old, generally accepted convention of private methods. Only we call such methods protected to indicate that they are inherited, but we will not use them externally. However, this is how they are used according to the ancient convention.
So, let's write a parent class with a protected method:
class User {
setName(name) {
this.name = name;
}
getName() {
return this._capeFirst(this.name);
}
_capeFirst(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Let's use this protected method in the descendant class:
class Student extends User {
setSurn(surn) {
this.surn = surn;
}
getSurn() {
return this._capeFirst(this.surn);
}
}
In the following code, make the helper method protected:
class User {
setName(name) {
if (this.notEmpty(name)) {
this.name = name;
}
}
getName() {
return this.name;
}
notEmpty(str) {
return str.length > 0;
}
}
class Employee extends User {
setSurn(surn) {
if (this.notEmpty(surn)) {
this.surn = surn;
}
}
getSurn() {
return this.surn;
}
}