기존의 방법으로, 어떠한 height와 width가 주어졌을 때 area를 구하는 instance 생성 방법은 아래와 같다.
//Area class 생성 function Area(height, width){ this.height = height; this.width = width; } //getArea instance 생성 Area.prototype.getArea = function(){ return this.height * this.width; } //적용 let myArea = new Area(30, 10); console.log(myArea.getArea()); // 300 console.log(myArea.height); // 30
WeakMap으로 외부 접근이 불가능하게 관리하는 instance는 다음과 같이 쓸 수 있다.
const weakMap = new WeakMap(); function Area(height, width){ weakMap.set(this, {height, width}); } Area.prototype.getArea = function(){ const {height, width} = weakMap.get(this); return height * width; } let myArea = new Area(30, 10); console.log(weakMap.has(myArea)); // true console.log(myArea.getArea()); // 똑같이 300 console.log(myArea.width); // undefined가 나오면서 접근이 불가능해진다. myarea = null; console.log(weakMap.has(myArea)); // false
Tagged Template literals - HTML, Javascript ES6 (0) | 2019.04.19 |
---|---|
Set으로 로또 추첨기 만들기 - Javascript ES6 (0) | 2019.04.19 |
Map 과 WeakMap - Javascript ES6 (0) | 2019.04.19 |
WeakSet으로 효과적인 객체 타입 저장 - Javascript ES6 (0) | 2019.04.19 |
Set으로 유니크한 배열 생성하기 - Javascript ES6 (0) | 2019.04.19 |
댓글 영역