Question 51

Question

Explain how to use WeakMap for private data storage in ES6 classes.

Answer

WeakMap is a fantastic tool for achieving private data storage within ES6 classes because it avoids memory leaks and offers controlled access to internal state.

Here's a breakdown of how it works:

  1. Understanding WeakMap:

    • A WeakMap stores key-value pairs where the keys must be objects, but the values can be any type.

    • Crucially, a WeakMap weakly references its keys. This means that if the object used as a key becomes unreachable (no other references to it exist), the corresponding entry in the WeakMap will automatically be garbage collected.

  2. Implementing Private Data with WeakMap:

    class MyClass {
      constructor() {
        this._data = new WeakMap(); // Create a private WeakMap
      }
    
      setData(key, value) {
        this._data.set(this, value); // Set data associated with this instance
      }
    
      getData(key) {
        return this._data.get(this, key);  // Retrieve data associated with this instance
      }
    }
    
    const myInstance = new MyClass();
    myInstance.setData('name', 'Alice'); // Set private data 
    console.log(myInstance.getData('name')); // Access private data

Explanation:

  • We create a WeakMap instance (_data) within the constructor of our class. This map will store private data associated with each individual instance of MyClass.

  • setData() sets key-value pairs in the _data map, using the current this object (the instance) as the key.

  • getData() retrieves values from the _data map based on the provided key and the current instance (this).

Why Use WeakMap?

  • Memory Safety: Because WeakMap uses weak references, if an instance of MyClass is no longer referenced anywhere else in your code, its data will be automatically cleaned up by the garbage collector. This prevents memory leaks.

  • Encapsulation: It effectively hides internal state from external access, promoting better encapsulation and data protection within your class.

Last updated