← JavaScript

Advanced · 8 of 11 · 20 min read

Proxy and Reflect

Intercepting the fundamental operations on an object, the traps worth knowing, and why Reflect belongs in every handler.

  • Proxy & Reflect

A Proxy wraps an object and lets you intervene in the basic operations performed on it — reading a property, writing one, deleting one, asking whether it exists. It is the closest JavaScript gets to metaprogramming.

The shape

const target = { name: 'Ana', age: 30 };

const proxy = new Proxy(target, {
  get(obj, property, receiver) {
    console.log('reading', property);
    return Reflect.get(obj, property, receiver);
  },
  set(obj, property, value, receiver) {
    console.log('writing', property);
    return Reflect.set(obj, property, value, receiver);
  },
});

console.log(proxy.name); // "reading name" then "Ana"
proxy.age = 31;          // "writing age"
console.log(target.age); // 31 — the target really changed

The proxy is a separate object that forwards to the target. With an empty handler it is transparent:

const plain = new Proxy({ a: 1 }, {});
console.log(plain.a, Object.keys(plain)); // 1 ["a"]

The traps worth knowing

Trap Intercepts
get obj.x, obj['x']
set obj.x = v
has 'x' in obj
deleteProperty delete obj.x
ownKeys Object.keys, for...in, spread
apply calling a function target
construct new on a function target
getPrototypeOf instanceof, Object.getPrototypeOf

There are thirteen in total, one per internal method in the spec, and the four above the line cover almost every real use.

Default values, instead of undefined

const withDefault = (obj, fallback) =>
  new Proxy(obj, {
    get: (target, prop) => (prop in target ? target[prop] : fallback),
  });

const counts = withDefault({ a: 1 }, 0);
console.log(counts.a, counts.zzz); // 1 0 — no undefined anywhere

Validation on write

The trap returns a boolean saying whether the write succeeded; returning false throws in strict mode, so a module gets an error rather than a silent no-op.

const validated = new Proxy(
  { age: 30 },
  {
    set(target, prop, value) {
      if (prop === 'age') {
        if (typeof value !== 'number') throw new TypeError('age must be a number');
        if (value < 0 || value > 150) throw new RangeError('age out of range');
      }
      return Reflect.set(target, prop, value);
    },
  },
);

validated.age = 31;
console.log(validated.age); // 31

try {
  validated.age = 'old';
} catch (error) {
  console.log(error.message); // age must be a number
}

Hiding properties

A trap can lie about what exists — as long as it lies consistently, across get, has and ownKeys:

const hidePrivate = (obj) =>
  new Proxy(obj, {
    get: (t, p) => (String(p).startsWith('_') ? undefined : Reflect.get(t, p)),
    has: (t, p) => (String(p).startsWith('_') ? false : Reflect.has(t, p)),
    ownKeys: (t) => Reflect.ownKeys(t).filter((k) => !String(k).startsWith('_')),
    getOwnPropertyDescriptor: (t, p) =>
      String(p).startsWith('_') ? undefined : Reflect.getOwnPropertyDescriptor(t, p),
  });

const user = hidePrivate({ name: 'Ana', _password: 'secret' });
console.log(user.name);             // "Ana"
console.log(user._password);        // undefined
console.log('_password' in user);   // false
console.log(Object.keys(user));     // ["name"]
console.log({ ...user });           // { name: 'Ana' }

ownKeys alone is not enough: Object.keys filters its result by each key’s descriptor, which is why getOwnPropertyDescriptor has to agree.

A negative-index array

const negatable = (arr) =>
  new Proxy(arr, {
    get(target, prop, receiver) {
      const index = Number(prop);
      if (Number.isInteger(index) && index < 0) return target[target.length + index];
      return Reflect.get(target, prop, receiver);
    },
  });

const list = negatable(['a', 'b', 'c']);
console.log(list[0], list[-1], list[-2]); // a c b
console.log(list.length, list.map((x) => x.toUpperCase())); // 3 ["A","B","C"]

Reactivity, in twelve lines

The pattern behind Vue 3 — and a strong answer to “what would you use a Proxy for?”

let activeEffect = null;
const subscribers = new Map();

function reactive(obj) {
  return new Proxy(obj, {
    get(target, prop, receiver) {
      if (activeEffect) {
        if (!subscribers.has(prop)) subscribers.set(prop, new Set());
        subscribers.get(prop).add(activeEffect); // track who read this
      }
      return Reflect.get(target, prop, receiver);
    },
    set(target, prop, value, receiver) {
      const result = Reflect.set(target, prop, value, receiver);
      subscribers.get(prop)?.forEach((effect) => effect()); // re-run them
      return result;
    },
  });
}

function watchEffect(fn) {
  activeEffect = fn;
  fn();              // the first run records the dependencies
  activeEffect = null;
}

const state = reactive({ count: 0 });
watchEffect(() => console.log('count is', state.count)); // count is 0
state.count = 5;                                          // count is 5

Reading inside an effect registers a dependency; writing notifies it. That is the entire idea, and it is why a Proxy replaced the Object.defineProperty approach of Vue 2 — a proxy sees new properties and array index writes, which per-property getters could not.

Function traps

apply and construct intercept calls and construction:

function add(a, b) { return a + b; }

const logged = new Proxy(add, {
  apply(target, thisArg, args) {
    console.log(`calling with ${args}`);
    const result = Reflect.apply(target, thisArg, args);
    console.log(`returned ${result}`);
    return result;
  },
});

console.log(logged(2, 3)); // calling with 2,3 / returned 5 / 5

class User {}
const counted = new Proxy(User, {
  construct(target, args, newTarget) {
    console.log('constructing');
    return Reflect.construct(target, args, newTarget);
  },
});
console.log(new counted() instanceof User); // constructing / true

Why Reflect

Reflect is a namespace of plain functions, one for each internal operation a trap can intercept. Inside a handler it is the correct way to perform the default behaviour, for two reasons.

It forwards the receiver, which keeps inherited getters working:

const target = {
  _value: 'from target',
  get value() { return this._value; }, // `this` matters here
};

const broken = new Proxy(target, {
  get: (t, p) => t[p],                     // `this` is the target
});
const correct = new Proxy(target, {
  get: (t, p, receiver) => Reflect.get(t, p, receiver), // `this` is the proxy
});

const child = Object.create(correct);
child._value = 'from child';
console.log(child.value); // "from child" — the getter saw the right receiver

const childBroken = Object.create(broken);
childBroken._value = 'from child';
console.log(childBroken.value); // "from target" — the receiver was lost

It returns a boolean instead of throwing, which is exactly what set, defineProperty and deleteProperty must return:

const frozen = Object.freeze({ a: 1 });

console.log(Reflect.set(frozen, 'a', 2)); // false — reportable
try {
  'use strict';
  // frozen.a = 2;                        // TypeError — not reportable
} catch {}

console.log(Reflect.has({ a: 1 }, 'a'));  // true — the functional form of `in`
console.log(Reflect.ownKeys({ a: 1 }));   // ["a"] — includes symbols, unlike Object.keys
Operator Reflect equivalent
obj.x Reflect.get(obj, 'x')
obj.x = v Reflect.set(obj, 'x', v)
'x' in obj Reflect.has(obj, 'x')
delete obj.x Reflect.deleteProperty(obj, 'x')
new Fn(...args) Reflect.construct(Fn, args)
fn.apply(thisArg, args) Reflect.apply(fn, thisArg, args)

Reflect is useful outside proxies too — Reflect.ownKeys is the only built-in that returns string and symbol keys, including non-enumerable ones.

The invariants

A proxy cannot lie arbitrarily. The engine enforces the object invariants, and a trap that breaks one throws:

const target = {};
Object.defineProperty(target, 'fixed', { value: 1, writable: false, configurable: false });

const liar = new Proxy(target, {
  get: () => 'something else',
});

// console.log(liar.fixed);
// TypeError: 'get' on proxy: property 'fixed' is a read-only, non-configurable data
// property on the proxy target but the proxy did not return its actual value

Similarly, ownKeys must report every non-configurable own key of the target, and has cannot hide one. The rule of thumb: you can intercept, log and validate freely; you cannot contradict a non-configurable property.

Costs

A proxied access is substantially slower than a direct one — every read goes through a JavaScript function the engine cannot inline. That is fine for a config object or a dev-mode guard, and not fine in a hot loop over a large array.

// Reasonable: a few hundred accesses, in exchange for validation or tracking.
// Unreasonable: proxying a 100k-element array inside a render loop.

Also note: Proxy cannot be polyfilled. Its behaviour is not expressible in JavaScript, which is why Vue 2 used Object.defineProperty and supported IE, and Vue 3 does not.

Common mistakes

Using the operator instead of Reflect inside a trap

Mistake. get: (target, prop) => target[prop]. Why it fails. The receiver is dropped, so an inherited getter sees the wrong this — a subtle bug that only appears once something inherits from the proxy. What to do instead. Reflect.get(target, prop, receiver), and pass receiver through.

Forgetting the return value of set

Mistake. A set trap that assigns and returns nothing. Why it fails. undefined is falsy, which means “the write failed” — and in strict mode that throws a TypeError even though the write worked. What to do instead. return Reflect.set(...), or return true.

Comparing a proxy with its target

Mistake. proxy === target. Why it fails. They are different objects, so identity checks, Set membership and Map keys all treat them as two things. What to do instead. Pick one identity for the object and use it consistently — and keep a WeakMap from proxy to target if you need to recover it.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

A Proxy can sit in front of an object and intervene on every property read.

What does this log?

Code sample
const target = { a: 1 };
const proxy = new Proxy(target, {
  get: (obj, prop) => (prop in obj ? obj[prop] : "missing"),
});

console.log(proxy.a, proxy.b);

What is a Proxy "trap"?

What is Reflect actually for?

Practise Proxy & Reflect →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.