상세 컨텐츠

본문 제목

WeakMap으로 class의 instance 변수 보호하기 - Javascript ES6

Programming/Concept

by 쌩우 2019. 4. 19. 15:13

본문

기존의 방법으로, 어떠한 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



관련글 더보기

댓글 영역