Javascript - Create private property via Symbol

Introduction

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

Demo

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

Result

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