Old-Style Privacy in JavaScript OOP
Declaring private properties and methods via the # symbol is a fairly recent addition to JavaScript. Before that, you had to use a special tricky method.
The idea behind this technique is to agree that the names of private properties and methods should begin with an underscore. In reality, such names will not be private, but we agree that we will not use them from outside the class.
Let's try it. Let's make a private property in this style:
javascriptclass User {
constructor(name) {
this._name = name;
}
show() {
return this._name;
}
}
Let's create an object of the class:
javascriptlet user = new User('john', 'smit');
Let's call a method that outputs the value of our property:
javascriptconsole.log(user.show());
Trying to access a property from outside the class will not result in an error:
javascriptconsole.log(user._name); // there is no error
Задание 1
In the following code, make the properties private:
javascriptclass Employee {
constructor(name, salary) {
this.name = name;
this.salary = salary;
}
getName() {
return this.name;
}
getSalary() {
return this.salary;
}
}
Задание 2
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 + '$';
}
}