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:
let target = {};
let proxy = new Proxy(target, {});
proxy.name = "proxy";
console.log(proxy.name); // "proxy"
console.log(target.name); // "proxy"
target.name = "target";
console.log(proxy.name); // "target"
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?