liveBook · Manning

Proxy

As explained in The Joy of JavaScript

A Proxy is a JavaScript object that wraps a target object and intercepts fundamental operations on it through handler traps.

A Proxy is a JavaScript object that wraps a target and intercepts fundamental operations through handler traps. It looks and behaves like a regular object while allowing behavior to be woven in externally, preserving separation between application logic and cross-cutting concerns. section 7.6 section 7.6.1

A handler defines the operations a proxy can intercept:

  • Use get to observe property and method access, then delegate default behavior with target[key] or Reflect.get. section 7.6.1
  • Use set to react when selected properties change, such as recalculating a block hash. section 7.6.3
  • Use has to control how property existence is reported, such as hiding password fields. section 7.6.1
  • Compose multiple proxies to layer tracing and obfuscation without modifying the wrapped object. section 7.6.1

Tracing and masking credentials

Wrap a credentials object with a tracing handler to log reads and method calls. Add a second handler that returns bullets for password access and reports false for the password field with the in operator. The wrapped object remains unaware of both concerns. section 7.6.1

Automatic behavior in application objects

A proxy can monitor hashed blockchain properties and recalculate a block's hash after mutation. A revocable proxy can also measure validate execution time and later disable that instrumentation. section 7.6.3

Figure 7.2 The Proxy pattern uses an object (proxy) to act on behalf of a target. When fetching for a property, if it finds the property in the proxy, the code uses that property; otherwise, it consults the target object. Proxies have lots of uses, including logging, caching, and masking.

Use the diagram to see how a proxy acts on behalf of a target, consulting its own properties before delegating to the target, with logging, caching, and masking as applications. section 7.6

How The Joy of JavaScript covers it

How deep it goes
Explains targets, handlers, get, set, and has traps with examples, while stopping short of covering every available trap.
Examples
Demonstrates credential tracing and masking, composed handlers, automatic blockchain block hashing, and revocable validation timing.
What you can do after
Build it from scratch using Proxy handlers and Reflect to inject modular behavior around object access and mutation.
How it connects
Connects dynamic proxies with metaprogramming, reflection, Reflect, decorators, mixins, logging, caching, and performance profiling.

Also explained in

Compare how 3 books explain proxy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.