SyntaxStudy
Sign Up
JavaScript Advanced 5 min read

Proxy and Reflect

Proxy and Reflect

Proxy intercepts fundamental object operations. Reflect provides default implementations of those operations.

Example
const handler = {
  get(target, key) { return key in target ? target[key] : `No key: ${key}`; },
  set(target, key, val) { if (typeof val !== "number") throw TypeError("Numbers only"); return Reflect.set(target, key, val); }
};
const proxy = new Proxy({}, handler);
proxy.age = 30;  // OK
proxy.name = "x"; // TypeError
Pro Tip

Vue 3 and MobX use Proxy to build their reactivity systems.