Masterbook/Chapter 76• 1 min read
View Raw Code on GitHub

Proxy and Reflect Api

Proxy and Reflect APIs in JavaScript

JavaScript objects expose certain behaviours—reading a property, assigning a value, calling a function, checking membership—with built-in semantics. The Proxy API allows you to customize these fundamental operations by wrapping an object in an intermediary. The Reflect API complements Proxy by providing methods that perform the default behaviour of those operations in a uniform way.

Proxy: intercepting object operations

A proxy is created with new Proxy(target, handler). The target is the object being wrapped, and the handler is an object whose properties are functions (called traps) that intercept operations on the target. When an operation occurs, the corresponding trap executes; you can run custom logic, block the operation, or forward it to the original target using Reflect.

Basic usage

const person = { name: "Alice", age: 30 };
const handler = {
    get(target, prop, receiver) {
        console.log(`Reading property ${prop}`);
        return Reflect.get(target, prop, receiver);
    },
    set(target, prop, value, receiver) {
        if (prop === "age" && value < 0) {
            throw new Error("Age cannot be negative");
        }
        console.log(`Setting ${prop} to ${value}`);
        return Reflect.set(target, prop, value, receiver);
    },
};