Lesson 87 – JavaScript Proxy Object
In this lesson, you'll learn how to use the Proxy
object in JavaScript to intercept and redefine fundamental operations for objects.
What is a Proxy?
A Proxy allows you to create a wrapper around an object and customize its behavior for fundamental operations like property lookup, assignment, enumeration, function invocation, etc.
Syntax
const proxy = new Proxy(target, handler);
target
: The original object you want to proxy.handler
: An object containing traps (methods) that redefine the behavior.
Basic Proxy Example
const user = {
name: "Alice",
age: 30
};
const handler = {
get(target, property) {
return property in target ? target[property] : "Not Found";
}
};
const proxyUser = new Proxy(user, handler);
console.log(proxyUser.name); // Alice
console.log(proxyUser.email); // Not Found
Common Proxy Traps
Trap Name | Description |
---|---|
get |
Intercepts property access |
set |
Intercepts property assignment |
has |
Intercepts the in operator |
deleteProperty |
Intercepts delete operations |
ownKeys |
Intercepts Object.keys() and similar methods |
Example: Logging Access
const data = { value: 10 };
const logger = new Proxy(data, {
get(target, prop) {
console.log(`Accessing ${prop}`);
return target[prop];
},
set(target, prop, value) {
console.log(`Setting ${prop} to ${value}`);
target[prop] = value;
return true;
}
});
logger.value; // Logs: Accessing value
logger.value = 20; // Logs: Setting value to 20
Use Cases
- Data validation
- Property logging and tracking
- Access control
- Reactive programming (e.g. Vue.js)
Try Your Hand
const product = { name: "Book", price: 20 };
const secureProduct = new Proxy(product, {
set(target, prop, value) {
if (prop === "price" && value < 0) {
console.log("Price must be positive!");
return false;
}
target[prop] = value;
return true;
}
});
secureProduct.price = -5; // Should log a warning
secureProduct.price = 25; // Valid assignment
console.log(secureProduct.price); // 25
Summary
- Proxies allow you to intercept and customize object behavior.
- Use traps like
get
,set
,has
, and more. - Useful for validation, debugging, and advanced frameworks.