So let’s look at some examples and real world applications.

Syntax

Below is an example of proxy syntax where we pass in a target(in this case an empty object) and a handler.

proxy syntax

Common Object Property Lookup Behavior

common object property lookup behavior

In the snippet above we have a simple object with 2 keys(reason and code). Note the console logs on lines 7 and 8 return the key values. Then note the normal behavior on line 9. We attempt to retrieve a key(beer) which does not exist, so we receive undefined.

Proxied Object Property Lookup Behavior

proxied object lookup behavior

There is a bit more going on in this snippet. We define our handler(line 3) which is using the GET trap. The handler passes the target and the requested key name into the trap. Line 11 contains the same object from our Common Object Lookup example. Our proxy is instantiated on line 16.

Noting the console logs on lines 18 and 19 return the expected key values. But take a look at the rule from the log on line 20 — ‘key does not exist’.

We have overridden the default behavior for the operation with our custom proxy.

Using Proxies to enforce value validations