One of the new features introduced in the ES6 standard is the Proxy object. The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
You may run into some terms/concepts here shortly that are foreign to you, I encourage you to push through as the Proxy concept is actually fairly simple and useful.
There are 3 key terms we need to define before we proceed:
- handler — the placeholder object which contains the trap(s)
- traps — the method(s) that provide property access
- target — object which the proxy virtualizes
Check here for a list of all available traps.
So let’s look at some examples and real world applications.
Below is an example of proxy syntax where we pass in a target(in this case an empty object) and a handler.
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
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
In this snippet we define our handler on line 4. We then check to make sure that the age prop is the one being set and if so we validate on type and acceptable value range. There are custom error messages passed if validation fails. Otherwise, on line 16 we set the new prop value and return true to indicate a successful prop value set. Nothing to it.
- value correction
- property lookup extensions
- tracing property accesses
- revocable references
So that’s it for Proxies in ES6. Let us know your thoughts and questions on twitter. Keep after it.