Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Proxy Pattern Implementation in JavaScript

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Proxy Pattern runs in O(1) time and O(1) space, in JavaScript as in every other language.
  • ✓Proxy is a language built-in, not a pattern you implement. new Proxy(target, handler) accepts thirteen traps covering get, set, has, deleteProperty, ownKeys, apply and construct among others, and Reflect provides the matching default operation for each so a trap can do its work and then forward correctly.
  • ✓Always forward through Reflect rather than by touching the target directly, since Reflect mirrors the trap signatures exactly and returns the right value shape, including the boolean that set and deleteProperty must return in strict mode.
  • ✓The JavaScript trap: Proxies must honour the target invariants, and violating one throws a TypeError from the trap itself rather than from your code: a get trap may not report a different value for a property that is non-writable and non-configurable on the target, and ownKeys must include every non-configurable own key.
  • ✓Every operation on a proxy goes through the trap machinery, so property reads are typically an order of magnitude slower than on a plain object and, more importantly, the engine cannot install an inline cache for them: the access site stays generic forever.

What Proxy Pattern actually is

A proxy stands in front of a real object, satisfies the same interface, and gets to run code before, after or instead of forwarding each call. What separates these eight languages is a single question: can the runtime intercept a call the compiler already resolved? Two of them can, because attribute access is a hook you are allowed to override. One ships interception as a language primitive with a formal set of invariants. Two can do it only through bytecode generation at runtime, which is why their frameworks depend on it so heavily. And three cannot do it at all in the general case, so their answer is explicit forwarding, which the compiler helps with in different ways and which fails in one notorious shared way.

Proxy Pattern in JavaScript: what you actually reach for

Proxy is a language built-in, not a pattern you implement. new Proxy(target, handler) accepts thirteen traps covering get, set, has, deleteProperty, ownKeys, apply and construct among others, and Reflect provides the matching default operation for each so a trap can do its work and then forward correctly. Reflect.get with the receiver argument is the correct forwarding call when the target uses getters, because it preserves the this the getter should see.

JavaScript implementation

Always forward through Reflect rather than by touching the target directly, since Reflect mirrors the trap signatures exactly and returns the right value shape, including the boolean that set and deleteProperty must return in strict mode. Keep handlers small and composable. Use Proxy.revocable when the proxy must be invalidated later, so the target can be garbage collected rather than pinned by a live proxy.
javascript
const target = {
  _secret: 1,
  get doubled() { return this._secret * 2 },
};

const audited = new Proxy(target, {
  get(t, prop, receiver) {
    if (typeof prop === 'string' && prop.startsWith('_')) {
      throw new TypeError('private: ' + prop);
    }
    // Reflect + receiver so getters see the PROXY as 'this'.
    return Reflect.get(t, prop, receiver);
  },
  set(t, prop, value, receiver) {
    return Reflect.set(t, prop, value, receiver);   // must return a boolean
  },
});

audited.doubled;            // 2

// Private fields are keyed to the INSTANCE, so this throws:
class Counter { #n = 0; inc() { return ++this.#n } }
const p = new Proxy(new Counter(), {});
// p.inc();   // TypeError: Cannot read private member #n from an object whose class did not declare it

// Built-ins hold INTERNAL SLOTS: bind the method to the real target.
const m = new Proxy(new Map(), {
  get: (t, k, r) => {
    const v = Reflect.get(t, k, r);
    return typeof v === 'function' ? v.bind(t) : v;
  },
});
m.set('a', 1);

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The JavaScript-specific trap

Proxies must honour the target invariants, and violating one throws a TypeError from the trap itself rather than from your code: a get trap may not report a different value for a property that is non-writable and non-configurable on the target, and ownKeys must include every non-configurable own key. The other trap catches class authors: private fields declared with a hash are keyed to the actual instance, so calling a method that touches one through a proxy throws because the proxy is not that instance. Internal slots behave the same way, which is why proxying a Map and calling get on it fails unless the trap binds the method to the target.

Performance in JavaScript, beyond the O(1)

Every operation on a proxy goes through the trap machinery, so property reads are typically an order of magnitude slower than on a plain object and, more importantly, the engine cannot install an inline cache for them: the access site stays generic forever. A proxy in a hot loop is therefore a much larger cost than the trap body suggests. Proxies also deoptimise code that would otherwise have been specialised on the object shape, so passing one into an existing hot function can slow that function down for every caller. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Proxy Pattern between languages.

Real-World Applications

Proxy Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In JavaScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Proxy Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Proxy Pattern appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Proxy Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Proxy Pattern to build pattern recognition. In JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

Frequently Asked Questions

Which JavaScript type or library should I use for Proxy Pattern?

Proxy is a language built-in, not a pattern you implement. new Proxy(target, handler) accepts thirteen traps covering get, set, has, deleteProperty, ownKeys, apply and construct among others, and Reflect provides the matching default operation for each so a trap can do its work and then forward correctly. Reflect.get with the receiver argument is the correct forwarding call when the target uses getters, because it preserves the this the getter should see.

What is the most common JavaScript mistake when implementing Proxy Pattern?

Proxies must honour the target invariants, and violating one throws a TypeError from the trap itself rather than from your code: a get trap may not report a different value for a property that is non-writable and non-configurable on the target, and ownKeys must include every non-configurable own key. The other trap catches class authors: private fields declared with a hash are keyed to the actual instance, so calling a method that touches one through a proxy throws because the proxy is not that instance. Internal slots behave the same way, which is why proxying a Map and calling get on it fails unless the trap binds the method to the target.

How does Proxy Pattern actually perform in JavaScript?

Every operation on a proxy goes through the trap machinery, so property reads are typically an order of magnitude slower than on a plain object and, more importantly, the engine cannot install an inline cache for them: the access site stays generic forever. A proxy in a hot loop is therefore a much larger cost than the trap body suggests. Proxies also deoptimise code that would otherwise have been specialised on the object shape, so passing one into an existing hot function can slow that function down for every caller. Time complexity is O(1) and space is O(1).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Most AI and dev tools have a student plan. See which ones and how to claim them on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.