Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript Proxy() 객체란? 용도와 get 트랩 활용법 완벽 정리

JavaScript Proxy() 객체란?

Proxy() 객체는 ECMAScript 6(ES6)에서 새롭게 도입된 기능 중 하나로, 속성 조회(property lookup), 할당(assignment), 열거(enumeration), 함수 호출 등 객체의 기본적인 연산에 대해 사용자 지정 동작(custom behavior)을 정의할 수 있게 해주는 강력한 도구입니다.

Proxy() 객체를 이해하려면 먼저 다음 세 가지 핵심 용어를 알아야 합니다.

  • handler(핸들러) — 트랩(trap)들을 담고 있는 자리표시자(placeholder) 객체입니다.
  • traps(트랩) — 객체의 속성 접근을 가로채는 메서드입니다.
  • target(타깃) — 프록시가 가상화하는 대상이 되는 객체입니다.

문법(Syntax)

var p = new Proxy(target, handler);

일반 객체 사용 시 문제점

다음 예제에는 'p'라는 객체가 있으며 몇 가지 속성을 가지고 있습니다. 이때 객체에 정의되어 있지 않은 속성에 접근하면 아래 출력 결과처럼 undefined가 반환됩니다.

예제

<html>
<body>
<script>
   var p = {
      Name: 'Ram kumar',
      Age: 27
   };
   document.write(p.Name);
   document.write("</br>");
   document.write(p.Age);
   document.write("</br>");
   document.write(p.designation);
</script>
</body>
</html>

출력 결과

Ram kumar
27
undefined

Proxy()로 undefined 출력 제거하기

Proxy()를 사용하면 위와 같은 undefined 출력을 깔끔하게 처리할 수 있습니다. Proxy는 "get" 트랩을 통해 존재하지 않는 속성에 대한 접근을 가로챕니다. Proxy 내부에 정의된 핸들러는 타깃 객체와 요청된 키 이름을 "get" 트랩에 전달하여 원하는 값을 반환하도록 제어할 수 있습니다.

다음 예제에서 처음에는 객체 'p'에 designation과 role 속성이 존재하지 않습니다. 하지만 Proxy()를 적용하면 'get' 트랩이 객체와 그 속성들을 가로채고, 값이 할당되지 않은 속성에 대해서는 미리 정의한 기본값이 표시됩니다.

예제

<html>
<body>
<script>
   var p = {
      Name: 'Ram kumar',
      Age: 27
   };
   var handler = {
      get: function(target, prop) {
         return prop in target ? target[prop] : 'Content developer';
      }
   };
   var prox = new Proxy(p, handler);
   document.write(prox.Name);
   document.write("</br>");
   document.write(prox.Age);
   document.write("</br>");
   document.write(prox.designation);
   document.write("</br>");
   document.write(prox.role);
</script>
</body>
</html>

출력 결과

Ram kumar
27
content developer
content developer

이처럼 Proxy의 get 트랩을 활용하면 객체에 존재하지 않는 속성에 접근할 때 undefined 대신 원하는 기본값을 반환하도록 만들 수 있으며, 이 외에도 데이터 유효성 검사, 로깅, 접근 제어 등 다양한 상황에서 유용하게 활용됩니다.