JavaScript Proxy and Handler
Subject: JavaScript
In JavaScript, a Proxy is an object that wraps another object and intercepts its operations, allowing you to customize its behavior. This is done through a handler object that defines traps — methods to intercept fundamental operations such as property access, assignment, function calls, etc.
Syntax
- targetObject: The original object to wrap.
- handlerObject: Defines traps to intercept operations on the target.
Example 1: Basic Proxy with get Trap
Common Handler Traps
- get: Intercepts property access.
- set: Intercepts property assignment.
- apply: Intercepts function calls.
- deleteProperty: Intercepts property deletion.
- has: Intercepts the
inoperator. - ownKeys: Intercepts Object.keys(), Object.getOwnPropertyNames(), etc.
Example 2: set Trap for Validation
Example 3: Proxy for Logging
Example 4: Function Proxy using apply Trap
Key Takeaways
- Proxy allows intercepting and redefining fundamental operations on objects and functions.
- The handler object contains traps that customize behavior.
- Common use cases include validation, logging, security, lazy loading, and building frameworks.
- Proxies can wrap both objects and functions.
- Proxies enable meta-programming by modifying behavior at runtime.