# 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)