Getting Started with JavaScript Proxy

duncandean

Duncan Dean

Posted on November 17, 2019

Getting Started with JavaScript Proxy

Have you ever wished you could hook into the process of a fundamental operation on an object in JavaScript and extend it?

Using the Proxy object, we can intercept and define custom behaviour for operations like property lookup, assignment, and function invocation. Effectively, this allows us to overload these operators.

Background

Proxy was first introduced as a standard in the ES2015 specification. It resides under the idea of metaprogramming, specifically intercession (a type of reflection).

There are three important constituents when dealing with Proxy.

  1. handlers: These are placeholder objects which contain traps.
  2. traps: These are methods we can use to hook into operations. They provide property access.
  3. target: The object that our proxy virtualises. This is effectively the object that we are proxying access to.

Let's jump into a quick example.

Note that even though we never assigned a value to the property something, 42 was returned when we accessed it. This is a result of setting the get trap on our proxy. We essentially overloaded the . operator.

Interestingly, we can create a crude observable of an object using a Proxy.

Here we use the Reflect API to ensure that we are still setting the actual property and not just calling onChange().

Proxy in the Wild

Now that you understand some of the basics of Proxy we can take a look at how it is being used in some open source libraries to achieve some pretty neat functionality.

We'll take a look at comlink, a library that makes using WebWorkers much simpler without having to orchestrate all your messages between your worker and the main thread with postMessage(). It operates like RPC. You can expose an object with certain properties and methods from the WebWorker scope. These are wrapped as promises in the main thread scope that you can await.

An example of comlink usage:

Under the hood, when we call .wrap(), a Proxy is being created so that the fundamental operators can be overloaded to provide extra functionality.

Proxy has also been used extensively in popular UI frameworks to notify views of any model changes using the .set() trap.

The Proxy can be a powerful tool for intercession in JavaScript and has great power. Use it wisely. 😉

💖 💪 🙅 🚩
duncandean
Duncan Dean

Posted on November 17, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related