Reading history

JavaScript Proxy and Reflect

6 min read 2 views

Learn JavaScript Proxy and Reflect: get, set, has and ownKeys traps for default values, validation, logging and hidden fields.

A Proxy is a stand-in for an object. Code uses the proxy exactly as if it were the real object. Behind the scenes, you can step in whenever a property is read, written, deleted or listed. That makes it possible to log every change, return default values, reject bad data or hide private fields, all without changing the original object. Reflect is its partner: a set of functions that perform the normal behaviour, so your proxy can add a little extra and then carry on as usual.

In this lesson you will learn

  • Creating a Proxy with a target and a handler
  • The get, set, has and ownKeys traps
  • Default values, validation and logging with proxies
  • What the Reflect methods do and why traps use them
  • When a Proxy is worth using, and when it is not

You should know objects, object methods and getters and setters.

Traps: Stepping In on Object Operations

// A Proxy wraps an object and lets "traps" step in on operations
const student = { name: "Rafi", marks: 78 };

const watched = new Proxy(student, {
  get(target, prop, receiver) {
    console.log(`reading "${String(prop)}"`);
    return Reflect.get(target, prop, receiver);    // do the normal thing
  },
  set(target, prop, value, receiver) {
    console.log(`setting "${String(prop)}" to ${value}`);
    return Reflect.set(target, prop, value, receiver);
  }
});

console.log(watched.name);
watched.marks = 85;
console.log("original object changed too:", student.marks);

// Default values for missing keys
const prices = new Proxy({ rice: 82, dal: 135 }, {
  get: (target, prop) => (prop in target ? target[prop] : "not in stock")
});
console.log(prices.rice, "|", prices.mango);

// Validation: reject bad values before they are stored
const account = new Proxy({ balance: 0 }, {
  set(target, prop, value) {
    if (prop === "balance" && (typeof value !== "number" || value < 0)) {
      throw new TypeError(`balance must be a number of 0 or more, got ${value}`);
    }
    target[prop] = value;
    return true;          // tell JavaScript the assignment worked
  }
});
account.balance = 500;
console.log("balance:", account.balance);
try { account.balance = -50; } catch (e) { console.log(e.message); }

Output

reading "name"
Rafi
setting "marks" to 85
original object changed too: 85
82 | not in stock
balance: 500
balance must be a number of 0 or more, got -50
  • new Proxy(target, handler) creates the proxy. The target is the real object; the handler is an object whose methods are called traps.
  • The get trap runs on every property read, and set on every write. Here they log the operation and then call Reflect.get or Reflect.set to do the normal work.
  • Changes made through the proxy reach the target, because the proxy passes them on. The proxy stores nothing itself.
  • The prices proxy returns "not in stock" instead of undefined for missing keys.
  • The account proxy checks values before saving them. A set trap must return true when it succeeds; returning false makes the assignment fail with a TypeError in strict mode.

Reflect and More Traps

// Reflect has one method for each basic object operation
const book = { title: "Padma Nadir Majhi" };
console.log(Reflect.has(book, "title"));          // same as "title" in book
console.log(Reflect.ownKeys(book));                 // keys, including symbols
console.log(Reflect.defineProperty(book, "year", { value: 1936 }));  // returns true/false
console.log(Reflect.deleteProperty(Object.freeze({ a: 1 }), "a"));    // false instead of an error

// Hide "private" fields that start with an underscore
function hidePrivate(obj) {
  return new Proxy(obj, {
    has: (t, p) => !String(p).startsWith("_") && Reflect.has(t, p),
    ownKeys: t => Reflect.ownKeys(t).filter(k => !String(k).startsWith("_")),
    get: (t, p, r) => (String(p).startsWith("_") ? undefined : Reflect.get(t, p, r))
  });
}
const user = hidePrivate({ name: "Mitu", email: "mitu@example.com", _password: "secret123" });
console.log(Object.keys(user));
console.log("_password" in user, user._password);
console.log(JSON.stringify(user));

// Negative array indexes, like Python
const list = arr => new Proxy(arr, {
  get(t, p, r) {
    const i = Number(p);
    if (Number.isInteger(i) && i < 0) return t[t.length + i];
    return Reflect.get(t, p, r);
  }
});
const cities = list(["Dhaka", "Khulna", "Rajshahi", "Sylhet"]);
console.log(cities[-1], cities[-2], cities[0], cities.length);

Output

true
[ 'title' ]
true
false
[ 'name', 'email' ]
false undefined
{"name":"Mitu","email":"mitu@example.com"}
Sylhet Rajshahi Dhaka 4
  • Each Reflect method matches one trap and does the default job. Reflect.has(obj, key) works like the in operator.
  • Reflect methods report failure by returning false rather than throwing. Deleting a property from a frozen object returns false.
  • hidePrivate uses three traps. has controls the in operator, ownKeys controls Object.keys and JSON.stringify, and get hides the values.
  • The list proxy adds Python-style negative indexes, so cities[-1] is the last item. Note that property keys arrive as strings, so the trap converts them with Number.
TrapRuns onMatching Reflect method
getobj.x, obj[key]Reflect.get
setobj.x = 1Reflect.set
has"x" in objReflect.has
deletePropertydelete obj.xReflect.deleteProperty
ownKeysObject.keys, for...inReflect.ownKeys
applyCalling a function proxyReflect.apply

When to Use a Proxy

Proxies power several popular tools. Vue uses them to notice when data changes and update the page automatically. Testing libraries use them to record how objects are used. In everyday code, a simple function or a class with getters and setters is often clearer. Proxies add a small cost to every operation, so avoid them in code that runs millions of times.

Common Mistakes

  1. Changing the original object directly and expecting the traps to run. Only operations on the proxy are trapped.
  2. Forgetting return true in a set trap, which makes assignments fail in strict mode.
  3. Writing target[prop] instead of Reflect.get(target, prop, receiver) when the object has getters. Reflect passes the correct this.
  4. Treating a proxy as a security tool. Code that holds the original object can still read everything.

Practice Exercises

Exercise 1. Make a proxy that turns every string value into uppercase when it is read.

Show answer
const shout = obj => new Proxy(obj, {
  get(t, p, r) {
    const v = Reflect.get(t, p, r);
    return typeof v === "string" ? v.toUpperCase() : v;
  }
});
console.log(shout({ city: "Rajshahi", pop: 1 }).city);   // "RAJSHAHI"

Exercise 2. Make a read-only proxy: any attempt to set or delete a property should throw an error.

Show answer
const readOnly = obj => new Proxy(obj, {
  set() { throw new Error("This object is read-only"); },
  deleteProperty() { throw new Error("This object is read-only"); }
});

Frequently Asked Questions

What is the difference between a Proxy and Object.freeze?

Object.freeze only stops changes. A Proxy can run any code you like on each operation: logging, validating, converting values or computing missing ones.

Can I turn a proxy off later?

Yes. Proxy.revocable(target, handler) returns both a proxy and a revoke function. After you call revoke(), any use of the proxy throws a TypeError.

Summary

  • A Proxy wraps a target object, and handler traps step in on operations such as get, set and has.
  • Reflect methods perform the default behaviour, so traps can add logic and then carry on normally.
  • Proxies are good for defaults, validation, logging and hiding fields.
  • Use simpler tools when they are enough; proxies add a small cost to every operation.

Next: JavaScript Symbols.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *