Javascript - Class Private Properties via WeakMap

Introduction

A WeakMap is a new data type introduced in ES6.

They are a collection of keys and values with the constraint of having an object as the keys.

You can create a WeakMap using the following:

const myMap = new WeakMap(); 

and you can use set and get methods on the returned WeakMap to store and retrieve a value associated with it:

const myMap = new WeakMap(); 
const myObj = { name: "jack" }; 
myMap.set(myObj, "developer"); 
console.log(myMap.get(myObj)); 
// developer 

Here, we are using an object as the key to store a value inside a WeakMap.

You can use WeakMap to store private properties of a class, and it destroys those private properties whenever an instance associated with the class is destroyed.

const data = new WeakMap(); 

class Bus { 
        constructor(seats) { 
                data.set(this, { 
                        capacity: seats 
                }); 
        } 

        get seats() { 
                return data.get(this).capacity; 
        } 

        set seats(value) { 
                data.get(this).capacity = value; 
        } 
} 

const jet = new Bus(200); 
console.log(jet.capacity);                // undefined 
console.log(jet.seats);                   // 200 

Here, we are using a WeakMap to keep the data private and exposing setters and getters to interact with the private data of the class.

We have to keep your WeakMap hidden from the outside world.

Related Topic