JavaScript의 WeakMap은 키가 객체여야 하는 키-값 쌍의 모음입니다. 열쇠는 "약하다". 이는 키 개체에 대한 다른 참조가 없으면 해당 개체가 여전히 WeakMap에 있더라도 가비지 수집될 수 있음을 의미합니다.
키는 객체여야 합니다:
약한 참조:
반복 불가능:
개인 데이터에 유용함:
const weakMap = new WeakMap();
Method | Description |
---|---|
weakMap.set(key, value) | Adds a new key-value pair or updates an existing key. |
weakMap.get(key) | Retrieves the value associated with the key. |
weakMap.has(key) | Checks if the key exists in the WeakMap. |
weakMap.delete(key) | Removes the key-value pair associated with the key. |
const weakMap = new WeakMap();
const weakMap = new WeakMap(); const obj1 = { name: "Alice" }; const obj2 = { name: "Bob" }; // Adding key-value pairs weakMap.set(obj1, "Data for Alice"); weakMap.set(obj2, "Data for Bob"); // Accessing values console.log(weakMap.get(obj1)); // Output: "Data for Alice" // Checking existence console.log(weakMap.has(obj2)); // Output: true // Removing a key-value pair weakMap.delete(obj2); console.log(weakMap.has(obj2)); // Output: false
let obj = { key: "value" }; const weakMap = new WeakMap(); weakMap.set(obj, "Some data"); // Remove all references to `obj` obj = null; // The `WeakMap` entry for `obj` is automatically removed by garbage collection.
const privateData = new WeakMap(); class User { constructor(name) { privateData.set(this, { name }); } getName() { return privateData.get(this).name; } } const user = new User("Alice"); console.log(user.getName()); // Output: "Alice"
요약하자면 WeakMap은 약한 참조와 비공개 연결이 필요한 시나리오를 위해 설계된 전문 컬렉션입니다.
JavaScript에서 Map과 WeakMap의 주요 차이점은 키 처리, 가비지 수집 및 기능에 있습니다. 자세한 비교는 다음과 같습니다.
Feature | Map | WeakMap |
---|---|---|
Key Types | Keys can be any type: objects, primitives. | Keys must be objects. |
Garbage Collection | Does not rely on garbage collection; keys persist. | Keys are held weakly and can be garbage-collected. |
Iteration | Iterable (can use for...of, forEach, etc.). | Not iterable (cannot list keys or values). |
Size Property | Has a size property to get the number of entries. | No size property available. |
Use Case | General-purpose key-value storage. | Specialized for associating metadata or private data with objects. |
Performance | Slightly slower due to strong key references. | Faster for memory-sensitive operations due to weak references. |
const weakMap = new WeakMap();
const weakMap = new WeakMap(); const obj1 = { name: "Alice" }; const obj2 = { name: "Bob" }; // Adding key-value pairs weakMap.set(obj1, "Data for Alice"); weakMap.set(obj2, "Data for Bob"); // Accessing values console.log(weakMap.get(obj1)); // Output: "Data for Alice" // Checking existence console.log(weakMap.has(obj2)); // Output: true // Removing a key-value pair weakMap.delete(obj2); console.log(weakMap.has(obj2)); // Output: false
let obj = { key: "value" }; const weakMap = new WeakMap(); weakMap.set(obj, "Some data"); // Remove all references to `obj` obj = null; // The `WeakMap` entry for `obj` is automatically removed by garbage collection.
const privateData = new WeakMap(); class User { constructor(name) { privateData.set(this, { name }); } getName() { return privateData.get(this).name; } } const user = new User("Alice"); console.log(user.getName()); // Output: "Alice"
예:
const metadata = new WeakMap(); function trackElement(element) { metadata.set(element, { clicks: 0 }); } function incrementClicks(element) { const data = metadata.get(element); if (data) { data.clicks++; } } const button = document.createElement("button"); trackElement(button); incrementClicks(button); console.log(metadata.get(button)); // Output: { clicks: 1 }
예:
const map = new Map(); map.set(1, "value"); // Allowed map.set("key", "value"); // Allowed map.set({}, "value"); // Allowed const weakMap = new WeakMap(); weakMap.set({}, "value"); // Allowed weakMap.set(1, "value"); // TypeError: Invalid value used as weak map key
Feature | Map | WeakMap |
---|---|---|
Flexibility | General-purpose, flexible. | Specialized, limited use case. |
Performance | Persistent key references. | Memory-efficient with weak references. |
Suitability | Iteration and long-term storage. | Private data and ephemeral relationships. |
위 내용은 JS의 WeakMap이란 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!