add a protected property to a class in javascript

In JavaScript, we can achieve encapsulation and protected properties in classes using Symbols. Symbols have a unique identifier and can be used as a property key on objects. We can create a symbol as a private property and then define a getter method to access the property value.

Here's an example:

index.tsx
const _salary = Symbol('salary');

class Employee {
  constructor(name, salary) {
    this.name = name;
    this[_salary] = salary;
  }

  getSalary() {
    return this[_salary];
  }
}

const john = new Employee('John', 5000);

console.log(john.name);  // 'John'
console.log(john.getSalary());  // 5000
console.log(john._salary);  // undefined
344 chars
19 lines

In the above example, we create a Symbol _salary and use it to define the protected property in the Employee class. We can access the protected property using the getSalary() method. And when we try to access it directly, it returns undefined.

Note that this is not truly private, as someone could simply access the protected property by doing Object.getOwnPropertySymbols(john)[0], but it does provide a level of protection against accidental or unknowing manipulation of the property.

gistlibby LogSnag