GarbageCollection (GC03)
1: const element = document.getElementById('myElement');
2: const clickHandlers = new WeakMap(); // Use a WeakMap to store event handler
3: const handleClick = () => {
4: console.log('Element clicked!');
5: };
6: clickHandlers.set(element, handleClick); // Store the handler in the WeakMap, using the element as a weak key
7: element.addEventListener('click', clickHandlers.get(element));
Weak References (WeakMap) WeakMap will automatically remove handleClick entry after element will be removed from DOM and garbage collected // ... (the element might be removed from the DOM at some point) ... // Now, when the element is garbage collected, the WeakMap doesn't prevent it. The entry will be removed automatically // ... later, when the element is no longer needed, the click handler will be garbage collected automatically
GarbageCollection context:
ES6 context:
- (2024) Notes about JS Closures. #ES6
- (2024) Notes about Javascript asynchronous programming. #ES6
- (2022) Modern Javascript books #ES6 #Doc
- (2021) JS learning start point #ES6
- (2021) Maximilian Schwarzmüller Javascript lecture #ES6
- (2021) Javascript interview question from Happy Rawat #ES6
- (2021) Javascript tests #ES6
- (2016) New unique features of Javascript (updated). #ES6
Comments (
)

Link to this page:
http://www.vb-net.com/JavascriptES6/GC03.htm
|