Introducing Javascript ES6 Proxies

Written by _bengarrison | Published 2017/08/14
Tech Story Tags: javascript | web-development | technology | programming | javascript-es6-proxies

TLDRvia the TL;DR App

introducing javascript es6 proxies

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.

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

proxies to enforce value validation

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.

There are many real-world applications for Proxies

  • validation
  • value correction
  • property lookup extensions
  • tracing property accesses
  • revocable references
  • implementing the DOM in javascript

So that’s it for Proxies in ES6. Let us know your thoughts and questions on twitter. Keep after it.

If you like this article, please recommend and share to help others find it!


Published by HackerNoon on 2017/08/14