JavaScript Development Space

How to Use Proxy and Reflect in JavaScript

Proxy and Reflect

In JavaScript, both Proxy and Reflect are powerful features that work together to provide enhanced control over object behavior. Here’s a detailed overview of how they work and how you can use them effectively.

1. Working with Proxy

A Proxy is a wrapper around an object that allows you to intercept and redefine operations like property access, assignment, and function invocation.

Basic Syntax

js
1 const proxy = new Proxy(target, handler);
  • target: The original object you want to wrap.
  • handler: An object defining which operations will be intercepted.

Example

Here’s how you can use a proxy to log whenever a property is accessed or modified:

js
1 const target = { message: 'Hello, World!' };
2
3 const handler = {
4 get(target, prop) {
5 console.log(`Getting ${prop}`);
6 return target[prop];
7 },
8 set(target, prop, value) {
9 console.log(`Setting ${prop} to ${value}`);
10 target[prop] = value;
11 return true;
12 },
13 };
14
15 const proxy = new Proxy(target, handler);
16
17 // Access and modify the proxy
18 console.log(proxy.message); // Logs: Getting message
19 proxy.message = 'Hello, Proxy!'; // Logs: Setting message to Hello, Proxy!

Common Proxy Traps

  • get(target, prop): Traps property access.
  • set(target, prop, value): Traps property assignment.
  • has(target, prop): Traps the in operator.
  • deleteProperty(target, prop): Traps property deletion.
  • apply(target, thisArg, args): Traps function calls.
  • construct(target, args): Traps object instantiation.

2. Working with Reflect

The Reflect object provides methods for basic operations on objects. It's often used inside proxy traps to handle the default behavior.

Example:

Here’s how to use Reflect to maintain the default behavior within proxy handlers:

js
1 const handler = {
2 get(target, prop) {
3 console.log(`Getting ${prop}`);
4 return Reflect.get(target, prop); // Perform default behavior
5 },
6 set(target, prop, value) {
7 console.log(`Setting ${prop} to ${value}`);
8 return Reflect.set(target, prop, value); // Perform default behavior
9 },
10 };

Common Reflect Methods

  • Reflect.get(target, prop): Retrieves a property from the object.
  • Reflect.set(target, prop, value): Sets a property on the object.
  • Reflect.has(target, prop): Checks if the property exists (like the in operator).
  • Reflect.deleteProperty(target, prop): Deletes a property from the object.
  • Reflect.apply(target, thisArg, args): Calls a function with a specific this context and arguments.
  • Reflect.construct(target, args): Creates a new instance of an object (like new).

3. Practical Example: Validation with Proxy and Reflect

You can combine Proxy and Reflect to create objects that enforce certain rules, such as type checking or input validation.

js
1 const validator = {
2 set(target, prop, value) {
3 if (typeof value !== 'string') {
4 throw new Error(`Property ${prop} must be a string`);
5 }
6 return Reflect.set(target, prop, value); // Perform default set operation
7 },
8 };
9
10 const user = new Proxy({}, validator);
11
12 // Valid input
13 user.name = 'Margaret';
14
15 // Invalid input
16 user.age = 45; // Error: Property age must be a string

Conclusion

Proxy and Reflect provide a flexible way to customize object behavior in JavaScript. Proxy allows you to intercept fundamental operations, while Reflect ensures you can still maintain default behavior when needed. Together, they enable advanced use cases like data validation, logging, and more!

JavaScript Development Space

© 2024 JavaScript Development Space - Master JS and NodeJS. All rights reserved.