Hello! Welcome to the first lesson in our new module, "Metaprogramming with Proxies and Reflect."
In our previous module, we focused on controlling when and how often asynchronous code executes using patterns like debounce and throttle. Now, we're making a significant shift from controlling function execution to redefining the fundamental behavior of JavaScript objects themselves. This is the domain of metaprogrammingβwriting code that operates on other code.
Today, your goal is to create a Proxy to intercept and customize fundamental object operations. A Proxy object acts as a wrapper around another object (the "target"), allowing you to "trap" operations like property access, assignment, or function calls, and inject your own custom logic. This is one of the most powerful features in modern JavaScript for building dynamic and flexible APIs, frameworks, and tools.
1. The Concept of Intercession and the Need for Proxies
At its core, metaprogramming in JavaScript often involves three concepts: introspection (examining code), reflection (modifying code), and intercession (intercepting operations). Proxies are JavaScript's primary tool for intercession.
To understand why Proxies are so valuable, let's first look at the older, more cumbersome way to intercept property access.
JavaScript Metaprogramming - Dave Fancher - NDC London 2022
To appreciate the elegance of Proxies, it's helpful to see the problem they solve. This clip from the talk "JavaScript Metaprogramming" by Dave Fancher at NDC London 2022 demonstrates how Object.defineProperty can be used to intercept get and set operations, and highlights how verbose it becomes.
Watch the segment from 00:46:33 to 00:51:17. Pay attention to how a getter and setter must be defined for each individual property you want to audit. This sets the stage for a more general solution.
As you saw, using Object.defineProperty forces you to manually define interception logic for every single property. If you want to audit a 20-property object, you'd have to write 20 definitions. This doesn't scale and isn't dynamic.
This is precisely the problem Proxy was designed to solve.
2. Introducing the Proxy Object
A Proxy wraps a target object and allows you to define a handler containing "traps" that intercept operations.
The basic syntax is: let proxy = new Proxy(target, handler);
target: The original object you want to wrap.handler: An object whose properties are functions (the "traps") that define the custom behavior for different operations.
Let's start with the simplest case: a proxy with an empty handler.
const target = {
id: 1,
name: "Data Object"
};
const handler = {}; // An empty handler
const proxy = new Proxy(target, handler);
// Operations on the proxy are forwarded to the target
proxy.name = "Updated Object";
console.log(target.name); // "Updated Object"
console.log(proxy.id); // 1
With an empty handler, the proxy is completely transparent. It simply forwards all operations to the target. The real power comes when we add traps to the handler.
3. Traps and Internal Methods
How does a proxy actually "intercept" an operation like proxy.name? It does so by hooking into the JavaScript engine's internal methods.
Every standard operation on an object, like reading a property, corresponds to an internal method specified in the ECMAScript standard. For example:
- Reading a property (
obj.prop) triggers the[[Get]]internal method. - Assigning a property (
obj.prop = val) triggers the[[Set]]internal method. - Checking for a property's existence (
'prop' in obj) triggers the[[HasProperty]]internal method.
You can't call these internal methods directly, but you can define traps in a proxy handler that intercept them. Each trap has a name that corresponds to an internal method.
Proxy - JavaScript - MDN Web Docs - Mozilla
The MDN documentation provides an excellent explanation of this underlying mechanism. Reading this will clarify the connection between your proxy traps and the core workings of the JavaScript engine.
First, read the section "Object internal methods". This will give you the core theory. Then, briefly review the "Terminology" section to solidify the definitions of handler, trap, and target.
The javascript.info article provides a complete table of all available traps. You don't need to memorize it, but it's a valuable reference to see the full scope of what you can intercept.
This section of the javascript.info article on Proxies contains a comprehensive table listing all the proxy traps and the operations they correspond to.
Scan the table under the section that starts with 'For every internal method, thereβs a trap in this table...'. This will give you a sense of the breadth of operations you can intercept, from property access to function construction (new).
4. Implementing Your First Traps: get and set
Let's now implement the auditing example from the video, but this time using a Proxy to see how much cleaner it is. We only need to define a single get trap and a single set trap to handle any property.
JavaScript Metaprogramming - Dave Fancher - NDC London 2022
Now, let's watch the solution using a Proxy. This clip from the same NDC talk shows how to build the same auditing functionality with get and set traps, demonstrating its power and generality.
Watch from 00:51:17 to 00:56:27. Note how the handler with get and set methods applies to all properties of the target object, even ones that don't exist yet.
Here's the code, adapted from the video, for clarity:
const target = {
firstName: "John",
lastName: "Doe"
};
const handler = {
get(target, property) {
console.log(`Getting property '${property}'`);
// Forward the operation to the original object
return target[property];
},
set(target, property, value) {
console.log(`Setting property '${property}' to '${value}'`);
// Forward the operation to the original object
target[property] = value;
// The 'set' trap must return true on success
return true;
}
};
const user = new Proxy(target, handler);
// These operations will now be logged
console.log(user.firstName); // Logs "Getting property 'firstName'" and then "John"
user.age = 30; // Logs "Setting property 'age' to '30'"
Notice that we can intercept access to age even though it wasn't on the original target object. This dynamic capability is what makes Proxies so powerful.
Test your understanding!
Modify the set trap above. If a user tries to set the id property, throw an error with the message "ID property is read-only". For all other properties, allow the assignment to proceed.
Show answer
const handler = {
get(target, property) {
console.log(`Getting property '${property}'`);
return target[property];
},
set(target, property, value) {
if (property === 'id') {
throw new Error("ID property is read-only");
}
console.log(`Setting property '${property}' to '${value}'`);
target[property] = value;
return true;
}
};
const user = new Proxy({ name: 'Alice' }, handler);
user.name = 'Bob'; // Works
console.log(user.name); // Bob
try {
user.id = 123; // Throws an error
} catch (e) {
console.error(e.message); // "ID property is read-only"
}
The Role of Reflect
In our examples, we used target[property] to read from and write to the target object. This works, but it's not the best practice. The modern, recommended approach is to use the global Reflect object.
Reflect is a built-in object whose methods correspond one-to-one with the proxy traps. For example, Reflect.get() is the default implementation of the [[Get]] internal method.
Using Reflect ensures that you are safely and correctly forwarding the operation, especially in complex cases involving getters and inheritance.
This section of the javascript.info article explains why Reflect.get is safer than target[prop], particularly when dealing with getters and inheritance. The explanation of the receiver argument is a crucial piece of deep JavaScript knowledge.
Read the sections "Reflect" and "Proxying a getter". Focus on understanding the problem that receiver solves and why Reflect.get(...arguments) is the most robust way to forward a get operation.
After reading that, our handler should be updated to use Reflect:
const betterHandler = {
get(target, property, receiver) {
console.log(`Getting property '${property}'`);
// Use Reflect.get, passing all arguments along.
return Reflect.get(target, property, receiver);
},
set(target, property, value, receiver) {
console.log(`Setting property '${property}' to '${value}'`);
// Use Reflect.set. It handles forwarding and returns true/false for success.
return Reflect.set(target, property, value, receiver);
}
};
Rule of thumb: Inside a proxy trap, always use the corresponding Reflect method to forward the operation to the target.
5. Intercepting Other Operations
Proxies are not limited to getting and setting properties. You can intercept a wide range of fundamental operations. Let's look at two more examples to see the versatility.
Intercepting the in operator with has
You can redefine what it means for a property to be "in" an object. This allows for creative abstractions, like checking if a number falls within a range.
const range = { start: 1, end: 100 };
const rangeHandler = {
has(target, prop) {
const num = Number(prop);
// Check if the property is a number and is within the range
return !isNaN(num) && num >= target.start && num <= target.end;
}
};
const numberRange = new Proxy(range, rangeHandler);
console.log(50 in numberRange); // true
console.log(101 in numberRange); // false
console.log('start' in numberRange); // false, because 'start' is not a number
Intercepting function calls with apply
You can even wrap a function in a proxy. The apply trap intercepts calls to the function, allowing you to modify arguments, log calls, or add behavior before or after execution.
function greet(name) {
return `Hello, ${name}!`;
}
const functionHandler = {
apply(targetFunction, thisArg, argumentsList) {
console.log(`Calling function '${targetFunction.name}' with arguments:`, argumentsList);
// Call the original function using Reflect.apply
const result = Reflect.apply(targetFunction, thisArg, argumentsList);
console.log('Function returned:', result);
return result.toUpperCase(); // We can even modify the return value
}
};
const proxiedGreet = new Proxy(greet, functionHandler);
console.log(proxiedGreet("World"));
// Logs: Calling function 'greet' with arguments: [ 'World' ]
// Logs: Function returned: Hello, World!
// Final output: HELLO, WORLD!
Conclusion
In this lesson, we've unlocked a powerful feature of the JavaScript language. You now have the ability to go beyond using objects and functions as they are, and can start redefining their core behavior to suit your needs.
Key Takeaways:
- Metaprogramming is code that operates on other code; intercession is a form of it where you intercept and customize operations.
- The
Proxyobject creates a wrapper around atargetobject, intercepting operations via ahandler. - Traps are functions in the
handlerthat correspond to the engine's internal methods (e.g.,[[Get]],[[Set]]). - You can intercept a wide variety of operations, including property access (
get,set), existence checks (has), and function calls (apply). - The
Reflectobject provides methods that are the default implementation for each trap, and it is the best practice for forwarding operations from a trap to the target.
Next Up
You now understand the fundamental mechanism of creating and using a Proxy. In our next lesson, we will focus on a very common and powerful application of this knowledge: implementing validation and type-checking for object properties using get and set traps. We will build a proxy that enforces a schema on an object, ensuring data integrity at runtime.