WeakMap ऑब्जेक्ट में एलिमेंट्स की-वैल्यू पेयर के रूप में होते हैं जहां की एक ऑब्जेक्ट होनी चाहिए और वैल्यू कोई भी प्रिमिटिव वैल्यू या ऑब्जेक्ट हो सकती है। जिन ऑब्जेक्ट्स को WeakMap में की के रूप में उपयोग किया जाता है, वे गार्बेज कलेक्ट हो जाते हैं यदि उनका कोई रेफरेंस नहीं होता।
जावास्क्रिप्ट में WeakMap ऑब्जेक्ट के लिए कोड निम्नलिखित है:
उदाहरण
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>WeakMap object in JavaScript</h1> <div class="result"></div> <button class="Btn">Show WeakMap</button> <h3>Click on the above button to create and display a WeakMap object</h3> <button class="Btn">REMOVE</button> <h3>Click on the above button to remove reference of the WeakMap key</h3> <script> let resultEle = document.querySelector(".result"); let btnEle = document.querySelectorAll(".Btn"); let personObj = { name: "Rohan Sharma", age: 22, class: 9, }; let WeakMap1 = new WeakMap(); WeakMap1.set(personObj, "Rohan Object"); btnEle[0].addEventListener("click", () => { resultEle.innerHTML = "personObj : " + WeakMap1.get(personObj) + "<br>"; }); btnEle[1].addEventListener("click", () => { personObj = null; resultEle.innerHTML += "personObj : " + WeakMap1.get(personObj) + "<br>"; resultEle.innerHTML += " personObj is now removed from memory"; }); </script> </body> </html>
आउटपुट
उपरोक्त कोड निम्नलिखित आउटपुट उत्पन्न करेगा:

'Show WeakMap' बटन पर क्लिक करने पर:

'REMOVE' बटन पर क्लिक करने पर:
