작성자 : 배광식

검수자 : 장기효, 배광식

Proxy

속성 조회, 할당, 열거, 함수 호출 등 객체에 정의되어 있는 기본 동작을 변경하는데 사용하는 객체이다.

기본문법, 요소

const p = new Proxy(target, handler);
  • target : proxy 대상 객체

  • handler : target 객체에 대한 동작을 감지하여 trap 메서드를 호출

  • traps : target 객체의 기본 동작을 재정의한 메서드

기초예제

  • handler.get : 객체의 속성 값을 접근할 때의 동작을 정의

  • handler.set : 객체의 속성 값을 할당할 때의 동작을 정의

const target = {};
const handler = {
    get: function(target, property, receiver) {
        console.log(`getting ${property}`);
        return Reflect.get(target, property, receiver);
    },
    set: function(target, property, value, receiver) {
        console.log(`setting ${property}`);
        return Reflect.set(target, property, value, receiver);
    }
};
const proxy = new Proxy(target, handler);

proxy.count = 1;
// setting count

++proxy.count;
// getting count
// setting count

응용예제 - Read-only object

proxy를 이용하여 읽기만 가능한 객체를 만들수 있다.

const target = {};
const handler = {
    set: function(target, property, value, receiver) {
        throw new Error('This object is read-only');
    }
};
const p = new Proxy(target, handler);
p.count = 1;
// Error: This object is read-only

응용예제 - Validator

속성(property)이나 값(value)을 검증하는 로직을 정의할 수 있다.

const target = {};
const handler = {
    set: function(target, property, value, receiver) {
        if(property === 'num') {
            if(!Number.isInteger(value)) {
                throw new TypeError('num is not an integer');
            }
            if(value > 100) {
                throw new RangeError('num is out of range');
            }
        }
        target[property] = value;
        return true;
    }
};

const p = new Proxy(target, handler);
p.num = 10; // 10
p.num = 'hi'; // TypeError: num is not an integer
p.num = 200; // RangeError: num is out of range

proxy 취소 (revoke)

  • Proxy.revocable()을 통해 revoke() 함수를 활성화시킨다.
  • revoke()를 쓰면, proxy의 속성 접근을 차단시킨다.
const target = {};
const handler = {};
const {proxy, revoke} = Proxy.revocable(target, handler);

proxy.foo = 123;
console.log(proxy.foo); // 123

revoke();

console.log(proxy.foo); // TypeError : Revoked

results matching ""

    No results matching ""