JavaScript Proxy and Reflect API

JavaScript Proxy and Reflect API

JavaScript Proxy and Reflect API

The Proxy and Reflect APIs provide powerful ways to intercept and customize object behavior in JavaScript.

🔹 1. What is a Proxy?

A Proxy is an object that wraps another object and allows you to intercept operations like property access, assignment, function calls, etc.

📝 Basic Proxy Example

const target = { message: "Hello" }; const handler = { get(target, prop) { return prop in target ? target[prop] : `Property "${prop}" not found!`; } }; const proxy = new Proxy(target, handler); console.log(proxy.message); // Hello console.log(proxy.nonExistent); // Property "nonExistent" not found!

The get trap intercepts property access.
Returns a custom message if the property doesn’t exist.

🔹 2. Proxy Traps

A proxy handler can define various traps (methods that intercept operations):

TrapDescription
getIntercepts property access (obj.prop)
setIntercepts property assignment (obj.prop = value)
hasIntercepts in operator ("prop" in obj)
deletePropertyIntercepts property deletion (delete obj.prop)
applyIntercepts function calls (func())
constructIntercepts new operator (new obj())

📝 2.1. set Trap (Validation Example)

const user = { name: "Alice", age: 25 }; const handler = { set(target, prop, value) { if (prop === "age" && value < 0) { throw new Error("Age cannot be negative!"); } target[prop] = value; return true; // Must return `true` for successful assignment } }; const proxy = new Proxy(user, handler); proxy.age = 30; // ✅ Works // proxy.age = -5; // ❌ Throws Error: Age cannot be negative! console.log(proxy.age); // 30

Intercepts property assignments and applies validation.

📝 2.2. has Trap (in Operator Interception)

const user = { name: "John", password: "secret" }; const handler = { has(target, prop) { return prop !== "password"; // Hide `password` property } }; const proxy = new Proxy(user, handler); console.log("name" in proxy); // true console.log("password" in proxy); // false

Prevents access to sensitive properties using the in operator.

📝 2.3. deleteProperty Trap (Prevent Deletion)

const user = { name: "John", role: "admin" }; const handler = { deleteProperty(target, prop) { if (prop === "role") { throw new Error("Cannot delete role property!"); } delete target[prop]; return true; } }; const proxy = new Proxy(user, handler); // delete proxy.role; // ❌ Throws Error delete proxy.name; // ✅ Works console.log(proxy); // { role: "admin" }

Prevents deletion of critical properties.

📝 2.4. apply Trap (Intercept Function Calls)

const sayHello = (name) => `Hello, ${name}!`; const handler = { apply(target, thisArg, args) { if (args.length === 0) { throw new Error("Name is required!"); } return target(...args); } }; const proxy = new Proxy(sayHello, handler); console.log(proxy("Alice")); // Hello, Alice! // console.log(proxy()); // ❌ Throws Error: Name is required!

Ensures function is called with required arguments.

🔹 3. What is Reflect?

The Reflect API provides methods for object operations, similar to Object methods, but designed for metaprogramming.

📝 Basic Reflect Example

const user = { name: "Alice" }; console.log(Reflect.has(user, "name")); // true Reflect.set(user, "age", 25); console.log(user.age); // 25

Reflect provides an alternative to traditional property access and modification.

🔹 4. Using Reflect with Proxy

The Reflect API is often used inside Proxy traps to maintain default behavior.

📝 Example: Reflect in Proxy

const user = { name: "Alice", age: 25 }; const handler = { get(target, prop) { console.log(`Getting property: ${prop}`); return Reflect.get(target, prop); }, set(target, prop, value) { console.log(`Setting ${prop} to ${value}`); return Reflect.set(target, prop, value); } }; const proxy = new Proxy(user, handler); proxy.age = 30; // Setting age to 30 console.log(proxy.age); // Getting property: age → 30

Reflect ensures standard behavior while allowing customization.

🔹 5. Summary

FeatureProxyReflect
PurposeIntercepts operationsProvides standard operations
Usagenew Proxy(target, handler)Reflect.method(target, args...)
CustomizationModify default behaviorMaintain default behavior
Common UseSecurity, validation, loggingUtility for property access

🚀 With Proxy and Reflect, JavaScript becomes more flexible for metaprogramming, security, and performance optimizations!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close