typestar

Proxy and Reflect in JavaScript

Intercepting property access, which is how observables are built.

function withDefaults(target, fallback) {
  return new Proxy(target, {
    get(object, key, receiver) {
      return key in object ? Reflect.get(object, key, receiver) : fallback;
    },
    has() {
      return true;
    },
  });
}

const settings = withDefaults({ theme: "dracula" }, "unset");
console.log(settings.theme, settings.editor, "anything" in settings);

const log = [];
const watched = new Proxy({}, {
  set(object, key, value) {
    log.push(`${String(key)}=${value}`);
    return Reflect.set(object, key, value);
  },
});
watched.tpm = 104;
watched.stars = 3;
console.log(log, watched.tpm);

How it works

  1. A handler implements the traps you care about.
  2. Reflect performs the default behavior inside a trap.
  3. Use it sparingly: it is invisible at the call site.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
561
Tokens
171
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 93 seconds.

Type this snippet

Step 1 of 4 in Objects under the hood, step 12 of 16 in Functions & patterns.

← Previous Next →