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:

javascriptclass 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:

javascriptclass 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:

javascriptclass 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:

javascriptlet user = new User('john');

Let's call a public method that uses the helper:

javascriptconsole.log(user.show());
Задание 1

In the following code, make the helper method private:

javascriptclass Employee {
  constructor(name, salary) {
    this.name = name;
    this.salary = salary;
  }
  
  getSalary() {
    return this.addSign(this.salary);
  }
  
  addSign(num) {
    return num + '$';
  }
}