Creating a Simple Proxy

When you use the Proxy constructor to make a proxy, you’ll pass it two arguments: the target and a handler. A handler is an object that defines one or more traps. The proxy uses the default behavior for all operations except when traps are defined for that operation. To create a simple forwarding proxy, you can use a handler without any traps:

  1. let target = {};
  2. let proxy = new Proxy(target, {});
  3. proxy.name = "proxy";
  4. console.log(proxy.name); // "proxy"
  5. console.log(target.name); // "proxy"
  6. target.name = "target";
  7. console.log(proxy.name); // "target"
  8. console.log(target.name); // "target"

In this example, proxy forwards all operations directly to target. When "proxy" is assigned to the proxy.name property, name is created on target. The proxy itself is not storing this property; it’s simply forwarding the operation to target. Similarly, the values of proxy.name and target.name are the same because they are both references to target.name. That also means setting target.name to a new value causes proxy.name to reflect the same change. Of course, proxies without traps aren’t very interesting, so what happens when you define a trap?