xxxxxxxxxx
// Create a WeakMap
const weakMap = new WeakMap();
// Create some objects
const obj1 = {};
const obj2 = {};
// Associate data with objects in the WeakMap
weakMap.set(obj1, "Data for obj1");
weakMap.set(obj2, "Data for obj2");
// Retrieve data using objects as keys
console.log(weakMap.get(obj1)); // "Data for obj1"
console.log(weakMap.get(obj2)); // "Data for obj2"
// Let's simulate losing all references to obj1
obj1 = null;
// obj1 is no longer accessible, so it can be garbage collected
// This means the associated data is also automatically removed
console.log(weakMap.get(obj1)); // undefined
console.log(weakMap.get(obj2)); // "Data for obj2" (still accessible)
// Create a WeakMap
const weakMap = new WeakMap();
// Create some objects
const obj1 = {};
const obj2 = {};
// Associate data with objects in the WeakMap
weakMap.set(obj1, "Data for obj1");
weakMap.set(obj2, "Data for obj2");
// Retrieve data using objects as keys
console.log(weakMap.get(obj1)); // "Data for obj1"
console.log(weakMap.get(obj2)); // "Data for obj2"
// Let's simulate losing all references to obj1
obj1 = null;
// obj1 is no longer accessible, so it can be garbage collected
// This means the associated data is also automatically removed
console.log(weakMap.get(obj1)); // undefined
console.log(weakMap.get(obj2)); // "Data for obj2" (still accessible)