Private Methods in OOP in JavaScript
Not only properties, but also methods can be private. Usually, helper methods are made private so that they cannot be accidentally called from outside the class.
Let's look at an example. Let's say we have the following class:
class User {
#name;
constructor(name) {
this.#name = name;
}
show() {
return this.#name;
}
}
Let's make a private method in this class that will take a string as a parameter and capitalize its first character:
class User {
#name;
constructor(name) {
this.#name = name;
}
show() {
return this.#name;
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Let's use our helper method inside another method:
class User {
#name;
constructor(name) {
this.#name = name;
}
show() {
return this.#cape(this.#name);
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Let's check. Let's create an object of our class:
let user = new User('john');
Let's call a public method that uses the helper:
console.log(user.show());
In the following code, make the helper method private:
class Employee {
constructor(name, salary) {
this.name = name;
this.salary = salary;
}
getSalary() {
return this.addSign(this.salary);
}
addSign(num) {
return num + '$';
}
}