Javascript - Create private property via Symbol


Custom classes can create private members using symbol, making them available privately to the other methods defined in the class.


const age = Symbol("age"); 
class Person { /* w  ww  .  j  a v a2s  .  c o  m*/
        constructor(value) { 
                this[age] = value; 
        getAge() { 
const jack = new Person(23); 
console.log(jack); // Person {} 
console.log(jack.age); // undefined 
console.log(jack[Symbol("age")]); // undefined 
jack.getAge(); // 23


Here, we have a Person class that creates a private property using Symbols to store the age of the person.

The property is non-enumerable since it returns an empty object and can only be accessed via the exposed getAge() method.

Since Symbols are always unique, accessing the private property by creating the symbol with the same label age: Symbol("age") will only create a new unique symbol, and it will not be able to access the desired property of the object.

Related Topic