# 09. Map & WeakMap

๐Ÿ‘‰๐Ÿป ์ด์ œ Map๊ณผ WeakMap์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด์ž

# โœจ WeakMap

WeakMap์€ ์ด์ „ ๊ฒŒ์‹œ๋ฌผ์˜ WeakSet ๊ณผ ๊ฐ™์ด ์ฐธ์กฐ๋ฅผ ๊ฐ€์ง„ ๊ฐ์ฒด๋งŒ ํ• ๋‹น ๊ฐ€๋Šฅํ•˜๋‹ค.

let wm = new WeakMap();
let myfun = function(){};

// ์ด ํ•จ์ˆ˜๊ฐ€ ์–ผ๋งˆ๋‚˜ ์‹คํ–‰๋์ง€?
wm.set(myfun, 0);
console.log(wm);

let count = 0;
for(let i=0; i<10; i++) {
  count = wm.get(myfun);
  count++;
  wm.set(myfun, count);
}

console.log(wm.get(myfun));

myfun = null;

console.log(wm.get(myfun));
console.log(wm.has(myfun));

# ๐Ÿ”Ž console


[object WeakMap] { ... }
10
undefined
false

# โœจ WeakMap ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜ ๋ณดํ˜ธ

# ๐Ÿ™…๐Ÿปโ€โ™€๏ธ ๋ณดํ˜ธํ•˜๊ธฐ ์ „,


function Area(height, width) {
  this.height=height;
  this.width=width;
}

Area.prototype.getArea = function(){
  return this.height * this.width;
}

let myarea = new Area(10,20);
console.log(myarea.getArea());
console.log(myarea.height);

# ๐Ÿ”Ž console


200
10

# ๐Ÿ™†๐Ÿปโ€โ™€๏ธ ๋ณดํ˜ธํ•œ ํ›„,


WeakMap์„ ํ™œ์šฉํ•˜์˜€๋”๋‹ˆ, ๊ฐ์ฒด๋ฅผ ๋ณดํ˜ธํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋๋‹ค!

const wm = new WeakMap();

function Area(height, width) {
  wm.set(this, {height, width});
}

Area.prototype.getArea = function(){
  const {height, width} = wm.get(this);
  return height * width;
}

let myarea = new Area(10,20);
console.log(myarea.getArea());
console.log(myarea.height);

# ๐Ÿ”Ž console


200
undefined

# Reference


https://www.inflearn.com/course/es6-๊ฐ•์ขŒ-์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ/dashboard (opens new window)

https://jsbin.com/ (opens new window)

Last Updated: 2021-10-27