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.
There are three important constituents when dealing with
- handlers: These are placeholder objects which contain traps.
- traps: These are methods we can use to hook into operations. They provide property access.
- 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
Interestingly, we can create a crude observable of an object using a
Here we use the Reflect API to ensure that we are still setting the actual property and not just calling
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
An example of comlink usage:
Under the hood, when we call
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