객체 프록시의 실제 사용 사례

표준 정의



프록시 개체를 사용하면 다른 개체에 대한 프록시를 생성할 수 있으며 해당 개체에 대한 기본 작업을 가로채고 재정의할 수 있습니다.



조금 단순화합시다.

넓은 의미에서 "핸들러를 사용하여 개체의 동작을 사용자 지정"합니다.

대상 및 처리기



Target은 Proxy가 적용되는 관심 객체입니다.

핸들러 또는 트랩은 대상에서 작업(예: Proxy , get 등)을 처리할 책임이 있는 set에 두 번째 매개 변수로 전달되는 함수입니다.

new Proxy(target, handler);


진술이 전달하려는 내용에 무게를 더할 몇 가지 예를 살펴보겠습니다.

기본값 처리



우승자와 우승 상품을 연결하고 참가한 모든 사람이 위로 상품을 받는 데 사용되는 스크립트를 고려하십시오.
if-else 명령문 또는 스위치의 긴 목록과 달리 코드를 더 깔끔하게 코딩하는 방법은 Proxy를 사용하는 것입니다.

const prizeRegistry = {
  karen: "First Prize - BMW X5",
  mark: "Second Prize - Scooty",
  athira: "Third Prize - Bicycle"
};

const prizeHandler = {
  get(obj, prop) {
    return prop in obj ?
      obj[prop] :
      "Consolation prize - Chocolate Bar";
  }
};

const prizeList = new Proxy(prizeRegistry, prizeHandler);

console.log(prizeList.karen);
// expected output: "First Prize - BMW X5"

console.log(prizeList.reena);
// expected output: "Consolation prize - Chocolate Bar"


입력 유효성 검사



사용자 입력은 오늘날 대부분의 애플리케이션에 톱니바퀴 역할을 합니다. 아이러니하게도 책임 있는 코드가 시간이 지남에 따라 엉망이 되는 결과로 데이터를 깨끗하게 유지하기 위해 유효성 검사를 수행해야 합니다.

const validator = {
  set(obj, prop, value) {
    if (prop === 'weight') {
      if (!Number.isInteger(value)) {
        throw new TypeError('The weight is not an integer');
      }
      if (value > 200) {
        throw new RangeError('The weight seems invalid');
      }
    }

    // The default behavior to store the value
    obj[prop] = value;

    // Indicate success
    return true;
  }
};

const fish = new Proxy({}, validator);

fish.weight = 100;
console.log(fish.weight); 
// expected output: 100
fish.weight = 'small';    // Throws an exception
fish.weight = 300;        // Throws an exception


속성으로 배열 항목 객체 찾기




const products = new Proxy([
  { name: 'Firefox', type: 'browser' },
  { name: 'SeaMonkey', type: 'browser' },
  { name: 'Thunderbird', type: 'mailer' }
],
{
  get(obj, prop) {
    // The default behavior to return the value; prop is usually an integer
    if (prop in obj) {
      return obj[prop];
    }

    // Get the number of products; an alias of products.length
    if (prop === 'number') {
      return obj.length;
    }

    let result;
    const types = {};

    for (const product of obj) {
      if (product.name === prop) {
        result = product;
      }
      if (types[product.type]) {
        types[product.type].push(product);
      } else {
        types[product.type] = [product];
      }
    }

    // Get a product by name
    if (result) {
      return result;
    }

    // Get products by type
    if (prop in types) {
      return types[prop];
    }

    // Get product types
    if (prop === 'types') {
      return Object.keys(types);
    }

    return undefined;
  }
});

console.log(products[0]);          // { name: 'Firefox', type: 'browser' }
console.log(products['Firefox']);  // { name: 'Firefox', type: 'browser' }
console.log(products['Chrome']);   // undefined
console.log(products.browser);     // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }]
console.log(products.types);       // ['browser', 'mailer']
console.log(products.number);      // 3



위 스니펫은 mozilla documentation 에서 가져온 것으로 프록시를 사용하여 개체 배열의 개체를 최적으로 찾을 수 있는 방법을 보여줍니다.
Proxy의 뛰어난 기능을 활용하여 코드를 더 깔끔하게 유지하고 유지하는 데 도움이 되는 다른 실제 사용 사례가 많이 있습니다.

P.S 이것들은 내가 하루 종일 사용하는 몇 가지이며 DOM 조작, 속성 전달과 같은 몇 가지가 더 있습니다. 확인하실 수 있습니다here.

도움이 되었기를 바랍니다. 건배 🍻

좋은 웹페이지 즐겨찾기