← Back to JavaScript Course | Chapter 7: OOP & Prototypes | Lesson 5 of 6

JS WeakMap और WeakSet

WeakMap और WeakSet objects को रखते हैं बिना computer को उन्हें फेंकने से रोके जब कोई और उन्हें इस्तेमाल न कर रहा हो, जैसे एक sticky note जो अपनी चीज़ के चले जाने पर गिर जाता है। ये memory बर्बाद होने से बचाने में मदद करते हैं।
Syntax
javascript
const weakMap = new WeakMap();
weakMap.set(objectKey, value);
const weakSet = new WeakSet();
weakSet.add(object);

WeakMap की बुनियादी बातें

WeakMap key-value pairs store करता है जहाँ keys objects होनी ज़रूरी हैं। यह उन keys को garbage collected होने से नहीं रोकता।

चूंकि किसी और के reference न रखने पर WeakMap की keys अभी भी garbage collected हो सकती हैं, WeakMap उन memory leaks से बचाता है जो एक regular Map तब बनाता जब आप entries साफ करना भूल जाते।

उदाहरण: WeakMap Basics

javascript
// Declare the constant `wm` as a new `WeakMap` instance
// Declare the constant `wm` as a new `WeakMap` instance
const wm = new WeakMap();
// Declare the constant `obj`, set to `{}`
// Declare the constant `obj`, set to `{}`
const obj = {};
// Call `wm.set(obj, "some data")`
// Call `wm.set(obj, "some data")`
wm.set(obj, "some data");
// Print `wm.get(obj)` to the console
// Print `wm.get(obj)` to the console
console.log(wm.get(obj));

WeakMap Object Keys

WeakMap keys objects होनी ज़रूरी हैं। Strings, numbers, और दूसरी primitive values keys नहीं हो सकतीं।

यह पाबंदी ही garbage-collection के फायदे को संभव बनाती है: primitives कभी उस तरह garbage collected नहीं होतीं जैसे object references होती हैं, इसलिए उन्हें keys के तौर पर allow करना कोई मतलब नहीं रखता।

उदाहरण: WeakMap Object Keys

javascript
const wm = new WeakMap();
const key = {};
wm.set(key, "value");
// wm.set("string", "value"); // TypeError: Invalid value used as weak map key
console.log(wm.get(key));

WeakSet की बुनियादी बातें

WeakSet objects store करता है। यह तब उपयोगी है जब आपको बस यह जानना हो कि कोई object जोड़ा गया है या नहीं।

एक regular Set के उलट, WeakSet iteration या size property support नहीं करता, WeakMap जैसे ही automatic-cleanup फायदे के बदले उन सुविधाओं को छोड़ते हुए।

उदाहरण: WeakSet Basics

javascript
// Declare the constant `ws` as a new `WeakSet` instance
// Declare the constant `ws` as a new `WeakSet` instance
const ws = new WeakSet();
// Declare the constant `obj`, set to `{}`
// Declare the constant `obj`, set to `{}`
const obj = {};
// Call `ws.add(obj)`
// Call `ws.add(obj)`
ws.add(obj);
// Print `ws.has(obj)` to the console
// Print `ws.has(obj)` to the console
console.log(ws.has(obj));

WeakMap और Private Data

एक WeakMap objects से जुड़ा data रख सकता है बिना उन objects में दिखने वाली properties जोड़े।

native private fields मौजूद होने से पहले private class fields को simulate करने का यह एक आम pattern है, क्योंकि बाहरी code के पास WeakMap को सीधे enumerate या access करने का कोई तरीका नहीं होता।

उदाहरण: WeakMap and Private Data

javascript
// Declare the constant `privateData` as a new `WeakMap` instance
// Declare the constant `privateData` as a new `WeakMap` instance
const privateData = new WeakMap();
// Define the class `User`
// Define the class `User`
class User {
  // Constructor taking `name`, runs when a new instance is created
  // Constructor taking `name`, runs when a new instance is created
  constructor(name) {
    // Call `privateData.set(this, { name })`
    // Call `privateData.set(this, { name })`
    privateData.set(this, { name });
  }
  // Define the method `getName` with no parameters
  // Define the method `getName` with no parameters
  getName() {
    // Return `privateData.get(this).name` from this function
    // Return `privateData.get(this).name` from this function
    return privateData.get(this).name;
  }
}
// Print `new User("Sam").getName()` to the console
// Print `new User("Sam").getName()` to the console
console.log(new User("Sam").getName());

Weak Collections कब इस्तेमाल करें

जब object का lifetime मायने रखता हो और आपको collection पर normal iteration की ज़रूरत न हो, तो WeakMap या WeakSet इस्तेमाल करें।

जब आप ऐसे objects से metadata जोड़ रहे हों जिनके lifetime के आप owner नहीं हैं, तो WeakMap/WeakSet इस्तेमाल करें, और बाकी सभी मामलों में plain Map/Set, क्योंकि वे कहीं ज़्यादा operations support करते हैं।

उदाहरण: When to Use Weak Collections

javascript
// Declare the constant `visited` as a new `WeakSet` instance
// Declare the constant `visited` as a new `WeakSet` instance
const visited = new WeakSet();
// Define the function `markVisited` taking `node`
// Define the function `markVisited` taking `node`
function markVisited(node) { visited.add(node); }
// Declare the constant `el`, set to `{}`
// Declare the constant `el`, set to `{}`
const el = {};
// Call `markVisited(el)`
// Call `markVisited(el)`
markVisited(el);
// Print `visited.has(el)` to the console
// Print `visited.has(el)` to the console
console.log(visited.has(el));
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी WeakMap key के लिए string या number इस्तेमाल करना, जो TypeError throw करता है; keys objects होनी चाहिए।
  2. किसी WeakMap पर loop करने या .size पढ़ने की कोशिश करना, जो मौजूद ही नहीं हैं।
  3. यह उम्मीद करना कि entries तब भी रहेंगी जब कुछ और key को refer न करे, क्योंकि उन्हें garbage collect किया जा सकता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.