JavaScript Proxy
What is a Proxy?
A Proxy is a special object that wraps another object and lets you intercept and control operations performed on that object.
A Proxy is a "guard" ("middleman") between your code and a real object.
A Proxy lets you run your own code whenever someone interacts with an object.
What Can a Proxy Do?
A Proxy can intercept when someone (or something) is:
- Reading a property (get)
- Setting a property (set)
- Deleting a property (deleteProperty)
- Checking if a property exists (has)
- Calling a function (apply)
- Constructing an object (construct)
Proxy Example
Example
// Create an Object
const user = { name: "Jan", age: 40 };
//Create a Proxy
const proxy = new Proxy(user, {
get(target, property) {
log("Getting: " + property);
return target[property];
},
set(target, property, value) {
log("Setting: " + property);
return target[property];
}
});
proxy.name = "John";
let text = proxy.name;
Try it Yourself »
Reflect with Proxy (Very Common)
Proxy lets you intercept operations on objects:
- Read a property
- Write a property
- Delete a property
- Check property existence
Example
// Create an Object
const user = { name: "Jan", age: 40 };
// Create a Proxy
const proxy = new Proxy(user, {
get(target, prop) {
// safe forwarding
return Reflect.get(target, prop);
},
set(target, prop, value) {
// safe forwarding
return Reflect.set(target, prop, value);
}
});
Try it Yourself »
Why Proxies?
Proxies allow you to:
- Add logging
- Validate changes
- Create reactive systems (like Vue.js)
- Auto-generate properties
- Protect sensitive data
- Create virtual or computed objects
- Intercept function calls
Proxy Traps
| Trap Name | Trigger |
|---|---|
| get | Reading a Property |
| set | Writing a Property |
| has | "prop" in obj is used |
| deleteProperty | Deleting a Property |
| apply | Calling a Function |
| construct | new is used |