Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Proxy is a built-in object in JavaScript that allows intercepting and redefining behavior of other objects. You can "wrap" an object and control access to its properties, their modification, deletion, function calls and much more.
Simply put, Proxy is like a "layer" between object and its usage.
const proxy = new Proxy(target, handler);
target — object you're wrapping.handler — object with interceptor functions (so-called "traps"), e.g.: get, set, has, deleteProperty.const user = { name: "Alice", age: 25 };
const proxy = new Proxy(user, {
get(target, prop) {
console.log(`Reading property "${prop}"`);
return target[prop];
},
});
console.log(proxy.name); // Reading property "name" → "Alice"
| Trap | Description |
|---|---|
get() | Reading property |
set() | Writing value to property |
has() | in operator |
deleteProperty() | Deleting property (delete) |
apply() | Function call |
construct() | Call via new |
defineProperty() | Working with Object.defineProperty() |
getOwnPropertyDescriptor() | Getting property descriptor |
const user = {
name: "Alice",
age: 25
};
const validatedUser = new Proxy(user, {
set(target, prop, value) {
if (prop === "age" && typeof value !== "number") {
throw new TypeError("Age must be a number");
}
target[prop] = value;
return true;
}
});
validatedUser.age = 30; // OK
validatedUser.age = "много"; // Error