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:
class User {
constructor(name) {
this._name = name;
}
show() {
return this._name;
}
}
Let's create an object of the class:
let user = new User('john', 'smit');
Let's call a method that outputs the value of our property:
console.log(user.show());
Trying to access a property from outside the class will not result in an error:
console.log(user._name); // there is no error
In the following code, make the properties private:
class Employee {
constructor(name, salary) {
this.name = name;
this.salary = salary;
}
getName() {
return this.name;
}
getSalary() {
return this.salary;
}
}
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 + '$';
}
}