Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความแตกต่างระหว่าง Map และ WeakMap ใน JavaScript

Map vs WeakMap

โครงสร้าง Key-Value คล้ายกัน แต่มีความแตกต่างสำคัญเรื่อง Garbage Collection และ Key Types

ความแตกต่างหลัก

FeatureMapWeakMap
Key TypesAny (Primitive, Object)Object Only (No Primitive)
GC BehaviorStrong Reference (กัน GC)Weak Reference (ไม่กัน GC)
IterableYes (keys, values, entries)No (Non-enumerable)
Size Property.sizeNo (.size ไม่มี)
Clear()มีมี (แต่ไม่จำเป็น)

Map Example

<script>
  const map = new Map();
  const objKey = {name: 'tutorialspoint'};
  
  map.set('first', 'a');
  map.set(3, ['c']);
  map.set(objKey, 3);
  map.set(['add', 'mapping'], 'd');
  
  console.log(map.has(2));        // false
  console.log(map.has('first'));  // true
  console.log(map.get('first'));  // 'a'
  console.log(map.get(objKey));   // 3
  console.log(map.size);          // 4
  map.clear();
  console.log(map.size);          // 0
</script>

WeakMap Example

<script>
  const wm = new WeakMap();
  const obj4 = {d: 4};
  const obj5 = {e: 5};
  
  wm.set(obj4, 'fourth');
  wm.set(obj5, 'fifth');
  wm.set(function() {}, 7); // Function Key OK
  
  console.log(wm.has(obj4));  // true
  console.log(wm.get(obj4));  // 'fourth'
  console.log(wm.delete(obj4)); // true
  wm.clear();
</script>

Use Cases: WeakMap

  • Private Data: เก็บข้อมูล Private ของ Object (ไม่โผล่ใน Keys)
  • Cache/Memoization: Key ถูก GC ได้ → Cache Auto-expire
  • Metadata: ผูก Metadata กับ Object โดยไม่กัน GC
  • DOM Node Data: เก็บข้อมูลสำหรับ Element

Private Data Pattern (WeakMap)

const privateData = new WeakMap();

class MyClass {
  constructor(secret) {
    privateData.set(this, { secret });
  }
  
  getSecret() {
    return privateData.get(this).secret;
  }
}