Metaprogramming in JavaScript with the Proxy Object

JavaScript Logo

The `Proxy` object, introduced in ES6, allows you to create a wrapper around another object (the target) and intercept fundamental operations like property lookup, assignment, and function invocation. This is a powerful tool for metaprogramming.

How It Works

You create a proxy with a target object and a handler object. The handler contains 'traps', which are methods that will be called when an operation is performed on the proxy.

Example: Validation Proxy

Let's create a proxy that validates data being set on an object.

const user = { name: 'Alice', age: 25 };

const validator = {
  set(target, key, value) {
    if (key === 'age' && (typeof value !== 'number' || value < 18)) {
      throw new TypeError('Age must be a number and at least 18.');
    }
    // If valid, perform the actual set operation
    target[key] = value;
    return true;
  }
};

const userProxy = new Proxy(user, validator);

userProxy.age = 30; // Works
console.log(userProxy.age); // 30

try {
  userProxy.age = 'twenty'; // Throws TypeError
} catch (e) {
  console.error(e.message);
}

Other common traps include `get` (for property access), `has` (for the `in` operator), and `apply` (for function calls).

Comments