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:
Understanding
WeakMap:A
WeakMapstores key-value pairs where the keys must be objects, but the values can be any type.Crucially, a
WeakMapweakly 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 theWeakMapwill automatically be garbage collected.
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
WeakMapinstance (_data) within the constructor of our class. This map will store private data associated with each individual instance ofMyClass.setData()sets key-value pairs in the_datamap, using the currentthisobject (the instance) as the key.getData()retrieves values from the_datamap based on the provided key and the current instance (this).
Why Use WeakMap?
Memory Safety: Because
WeakMapuses weak references, if an instance ofMyClassis 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