WeakMap 개체에는 키-값 쌍이 요소로 포함되며, 여기서 키는 개체여야 하고 값은 모든 기본 값 또는 개체일 수 있습니다. WeakMap에서 키로 사용되는 개체는 참조가 없는 경우 가비지 수집됩니다.
다음은 JavaScript의 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> 출력
위의 코드는 다음 출력을 생성합니다 -

'WeakMap 표시' 버튼 클릭 시 -

'제거' 버튼을 클릭하면 -
