-
Javascript ES6 Map,WeakMap key/value 구조Javascript (ES6) 2020. 7. 30. 22:18
// Map & WeakMap //map은 key/value 구조 let wm = new WeakMap(); let myfun = function(){}; // 이 함수가 얼마나 실행됐는지 알려고 할때. wm.set(myfun,0); //key, value console.log(wm); //WeakMap {ƒ => 0} let count = 0; for (let i=0; i<10; i++) { count = wm.get(myfun); //get value count++; wm.set(myfun, count); } console.log(wm); //WeakMap {ƒ => 10} myfun = null; console.log(wm.get(myfun)); //undefined (가비지 컬렉션으로 이동) //WeakMap 활용 (클래스 인스턴스 변수 보호(private)) const wm1 = new WeakMap(); function Area(height, width){ wm1.set(this, {height, width}); //private하게 사용 } Area.prototype.getArea = function (){ const {height, width} = wm1.get(this); return height * width; } let myarea = new Area(10,20); console.log(myarea.getArea()); //200 console.log(myarea.height); //undefined (외부에서 접근 x) console.log(wm1.has(myarea)); //true myarea = null; console.log(wm1.has(myarea)); //false
set, weakSet 은 배열(중복 적용 x)
map weakMap 은 key/value 구조 기억해두기.
'Javascript (ES6)' 카테고리의 다른 글
Javascript ES6 Tagged Template literals (0) 2020.08.03 Javascript ES6 Set,WeakSet 유니크한 배열 만들기 (0) 2020.07.29 Javascript ES6 Destructuring 디스트럭처링 (분해하기) (0) 2020.07.25 Javascript ES6 From 메소드 (배열로 만들어주기) (0) 2020.07.25 Javascript ES6 Array spread operator 배열 펼치기 (0) 2020.07.25