Privātās metodes OOP JavaScript
Privātas var būt ne tikai īpašības, bet arī metodes. Parasti privātas tiek padarītas palīgmetodes, lai tās nejauši nevarētu tikt izsauktas ārpus klases.
Apskatīsim piemērā. Pieņemsim, ka mums ir šāda klase:
class User {
#name;
constructor(name) {
this.#name = name;
}
show() {
return this.#name;
}
}
Izveidosim šajā klasē privāto metodi, kas parametru pieņems virkni un padarīs lielo burtu tās pirmo simbolu:
class User {
#name;
constructor(name) {
this.#name = name;
}
show() {
return this.#name;
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Izmantosim mūsu palīgmetodi citas metodes iekšienē:
class User {
#name;
constructor(name) {
this.#name = name;
}
show() {
return this.#cape(this.#name);
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Pārbaudīsim. Izveidosim mūsu klases objektu:
let user = new User('john');
Izsauksim publisko metodi, kas izmanto palīgmetodi:
console.log(user.show());
Šajā kodā padariet palīgmetodi par privātu:
class Employee {
constructor(name, salary) {
this.name = name;
this.salary = salary;
}
getSalary() {
return this.addSign(this.salary);
}
addSign(num) {
return num + '€';
}
}