Chapter 6. Managing Property Access with Proxies

Proxies are an interesting and powerful feature in ES6 that act as intermediaries between API consumers and objects. In a nutshell, you can use a Proxy to determine the desired behavior whenever the properties of an underlying target object are accessed. A handler object can be used to configure traps for your Proxy, which define and restrict how the underlying object is accessed, as we’ll see in a bit.

6.1 Getting Started with Proxy

By default, proxies don’t do much—in fact they don’t do anything. If you don’t provide any configuration, your proxy will just work as a pass-through to the target object, also known as a “no-op forwarding proxy,” meaning that all operations on the proxy object defer to the underlying object.

In the following piece of code, we create a no-op forwarding Proxy. You can observe how by assigning a value to proxy.exposed, that value is passed onto target.exposed. You could think of proxies as the gatekeepers of their underlying objects: they may allow certain operations to go through and prevent others from passing, but they carefully inspect every single interaction with their underlying objects.

const target = {}
const handler = {}
const proxy = new Proxy(target, handler)
proxy.exposed = true
console.log(target.exposed)
// <- true
console.log(proxy.somethingElse)
// <- undefined

We can make the proxy object a bit more interesting by adding traps. Traps allow you to intercept interactions with target

Get Practical Modern JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.