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
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 theWeakMap
will automatically be garbage collected.
Implementing Private Data with
WeakMap
:
Explanation:
We create a
WeakMap
instance (_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_data
map, using the currentthis
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 ofMyClass
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