02. Create Proxy

Proxies are special objects that allow you customize some of these operations. A proxy is created with two parameters:

  • handler: For each operation, there is a corresponding handler method that – if present – performs that operation. Such a method intercepts the operation (on its way to the target) and is called a trap (a term borrowed from the domain of operating systems).

  • target: If the handler doesn’t intercept an operation then it is performed on the target. That is, it acts as a fallback for the handler. In a way, the proxy wraps the target.

If the target is a function, two additional operations can be intercepted:

  • apply: Making a function call, triggered via

    • proxy(···)

    • proxy.call(···)

    • proxy.apply(···)

  • construct: Making a constructor call, triggered via new proxy(···)

Операции, не соответствующие handler автоматически перенаправляются в target.

При помощи прокси нельзя перехватить вызов метода. Это нельзя сделать потому, что вызов метода - это одновременно две операции: (1) get-получение метода, (2) apply вызов функции. Решением является proxy-перехватчик на get, который возвращает обработчик перехвата apply:

function traceMethodCalls(obj) {
  const handler = {
    get(target, propKey, receiver) {
      const origMethod = target[propKey];
      return function(...args) {
        const result = origMethod.apply(this, args);
        console.log(
          propKey + JSON.stringify(args) + " -> " + JSON.stringify(result)
        );
        return result;
      };
    }
  };
  return new Proxy(obj, handler);
}

Last updated