What is a Proxy?
Learn to intercept operations on an object with a Proxy.
What is a Proxy?
A Proxy is a special object that wraps another object and intercepts fundamental operations on it. These operations include reading, writing, deleting properties and checking existence with the in operator. Proxy is the standard way to do metaprogramming.
const proxy = new Proxy(target, handler);It has two parts: target is the original object to wrap, and handler is a plain object that declares which operations to intercept. When the handler is empty, the Proxy forwards every operation to the target unchanged.
Handler and traps
A handler is a plain object that holds methods called traps. Each trap intercepts a specific operation: get intercepts property reads, set intercepts writes, and has intercepts the in operator.
const handler = {
get(target, prop) {
return target[prop];
}
};When a trap fires, it receives target (the original object) and prop (the accessed property name). If the trap returns a value, the Proxy uses it, so you can customize reads and writes.
Exercise Create your first Proxy
Define an object named user with a name property. Create a proxy variable using new Proxy(user, {}) with an empty handler. Then log the property value with console.log(proxy.name).
Show example solution
const user = { name: 'Ayşe' };
const proxy = new Proxy(user, {});
console.log(proxy.name);
Test yourself
-
Which is valid Proxy creation syntax?
- Proxy.create(target, handler)
- target.proxy(handler)
- new Proxy(target, handler)
- new Proxy(target)
Show answer
new Proxy(target, handler) — Correct! new Proxy(target, handler) is the standard way to create a Proxy.
-
Create a Proxy with an empty handler
const user = { name: 'Ayşe' }; const proxy = new Proxy(user, ____);Show answer
const user = { name: 'Ayşe' }; const proxy = new Proxy(user, {}); -
Match the Proxy concepts
- Proxy
- wraps the object
- handler
- holds traps
- trap
- intercepts operation
- target
- real object