Metaprogramming with Proxy
Learn about the basics of proxy and how to create a dummy proxy.
We'll cover the following
In an earlier example, in the Injecting Multiple Properties lesson, we introduced a few missing properties like first
and last
into arrays. This is member injection; we knew what to introduce or inject at code writing time. While that’s fun and useful, member synthesis ups the challenge and the resulting benefits by a few notches:
- With synthesis, we can bring onboard new members into a class based on runtime context.
- We can also alter the behavior of existing methods or properties dynamically based on the current state at runtime.
To achieve this, we need the help of the Proxy
class. We’ll first explore this newly added class in JavaScript and then employ it for method synthesis.
The Proxy
class
Definition: An instance of the
Proxy
class stands in for another object or a function, also known as target, and can intercept or trap calls to fields, methods, and properties on its target.
To create a proxy, provide two things:
- A target—the proxy stands in for this.
- A handler—this traps and intercepts calls on the target.
Use the handler to trap any operation that may be performed on an object or a function. By default, if you don’t trap a call, it defaults to a method on Reflect
so that the calls are forwarded to the target.
Get hands-on with 1400+ tech skills courses.