Practical Applications of WeakMap:
Private Data Storage:
Store private data for objects that can't be accessed directly, ensuring data security.
const privateData = new WeakMap();
class Person {
constructor(name) {
privateData.set(this, { name });
}
getName() {
return privateData.get(this).name;
}
}
const person = new Person('Alice');
console.log(person.getName()); // Alice
Metadata Association:
Attach extra data (metadata) to objects without modifying them directly.
const metadata = new WeakMap();
const obj = {};
metadata.set(obj, { id: 1, info: "example" });
console.log(metadata.get(obj)); // { id: 1, info: "example" }
Event Listener Management:
Track event listeners to avoid memory leaks when elements are removed.
const listeners = new WeakMap();
const button = document.querySelector('button');
function clickHandler() {
console.log('Clicked!');
}
listeners.set(button, clickHandler);
button.addEventListener('click', clickHandler);
Caching Results:
Cache computed results to save processing time.
const cache = new WeakMap();
function compute(obj) {
if (cache.has(obj)) return cache.get(obj);
const result = obj.value * 2; // Example calculation
cache.set(obj, result);
return result;
}