Posted January 26Jan 26 You are reading Part 35 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 6]IntroductionJavaScript's Proxy and Reflect APIs provide powerful tools for intercepting and customizing fundamental operations on objects. The Proxy API allows developers to define custom behaviors for property access, function calls, and more. The Reflect API complements Proxies by standardizing built-in object operations.1. Understanding JavaScript ProxiesA Proxy acts as an intermediary between an object and the operations performed on it. It allows developers to define custom behavior when interacting with the object.Syntax:let proxy = new Proxy(target, handler); target: The original object being proxied.handler: An object containing traps that define how operations on the proxy should be intercepted.Example: Basic Proxy Usagelet user = { name: "Alice" }; let proxyUser = new Proxy(user, { get(target, property) { console.log(`Accessing ${property}`); return target[property]; } }); console.log(proxyUser.name); // Logs: "Accessing name", then "Alice" 2. Proxy Traps: Intercepting Object OperationsProxies use traps to define custom behaviors for fundamental object operations.Common Proxy Traps:TrapDescriptionget(target, prop, receiver)Intercepts property access.set(target, prop, value, receiver)Intercepts property assignment.deleteProperty(target, prop)Intercepts property deletion.has(target, prop)Intercepts in operator usage.apply(target, thisArg, args)Intercepts function calls.construct(target, args, newTarget)Intercepts object instantiation with new.Example: Validating Property Assignmentlet validator = { age: 25 }; let proxyValidator = new Proxy(validator, { set(target, prop, value) { if (prop === "age" && value < 0) { throw new Error("Age cannot be negative"); } target[prop] = value; return true; } }); proxyValidator.age = 30; // Valid // proxyValidator.age = -5; // Throws error 3. Using Reflect APIThe Reflect API provides utility functions that mirror object operations and simplify proxy handling.Example: Using Reflect for a Proxylet person = { name: "John", age: 25 }; let proxyPerson = new Proxy(person, { 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); } }); console.log(proxyPerson.name); // Logs: "Getting property: name", then "John" proxyPerson.age = 30; // Logs: "Setting age to 30" Why Use Reflect?Provides default behavior for intercepted operations.Ensures consistent, error-free handling of object operations.Simplifies debugging by logging operations explicitly.4. Practical Use Cases of Proxies1. Data Validationlet userInput = new Proxy({}, { set(target, prop, value) { if (typeof value !== "string") { throw new Error("Only strings are allowed"); } target[prop] = value; return true; } }); userInput.username = "Alice"; // Works // userInput.age = 30; // Throws error 2. Auto-tracking Property Accesslet logAccess = new Proxy({}, { get(target, prop) { console.log(`Property accessed: ${prop}`); return Reflect.get(target, prop); } }); console.log(logAccess.test); // Logs: "Property accessed: test" 3. Default Fallback Valueslet defaults = new Proxy({}, { get(target, prop) { return prop in target ? target[prop] : "Default Value"; } }); console.log(defaults.name); // Output: "Default Value" 5. When to Use Proxies & Reflect APIUse CaseBest ChoiceLogging property accessProxy with get trapData validationProxy with set trapApplying default valuesProxy with fallback logicEnhancing built-in object behaviorReflect APIYou are reading Part 35 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 6]
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.