Private Properties in OOP in JavaScript

Properties of an object that can be read and written from outside are called public. There are also private properties that will only be accessible within the class.

Private property names must start with the # character. In addition, such properties must be declared at the beginning of the class code. Let's do this:

javascriptclass User {
  #name;
}

Now let's write data to our property. This can be done, for example, in the class constructor:

javascriptclass User {
  #name;
  
  constructor(name) {
    this.#name = name;
  }
}

Now let's make a method that will return the value of our property:

javascriptclass User {
  #name;
  
  constructor(name) {
    this.#name = name;
  }
  
  show() {
    return this.#name;
  }
}

Let's create a class object, passing the user name as a parameter:

javascriptlet user = new User('john');

Trying to access our property directly outside the class will result in an error:

javascriptconsole.log(user.#name); // 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

And calling our method will allow us to read this property:

javascriptconsole.log(user.show()); // will bring out 'john'
Задание 1

In the Employee class, make three private properties: name, salary, and age.

Задание 2

Pass the values ​​of these properties as a constructor parameter.

Задание 3

Create a method that will output the employee's data.