0
0
JavascriptHow-ToBeginner · 3 min read

How to Create Proxy in JavaScript: Simple Guide

In JavaScript, you create a proxy using the Proxy constructor by passing a target object and a handler object with traps. The proxy lets you intercept and customize operations like property access or assignment on the target object.
📐

Syntax

The Proxy constructor takes two arguments:

  • target: The original object you want to wrap.
  • handler: An object containing traps (methods) that intercept operations on the target.

Example syntax:

const proxy = new Proxy(target, handler);
javascript
const proxy = new Proxy(target, handler);
💻

Example

This example shows how to create a proxy that logs every time a property is read from the object.

javascript
const target = { message: 'Hello' };

const handler = {
  get(obj, prop) {
    console.log(`Property '${prop}' was accessed.`);
    return obj[prop];
  }
};

const proxy = new Proxy(target, handler);

console.log(proxy.message);
Output
Property 'message' was accessed. Hello
⚠️

Common Pitfalls

Common mistakes when creating proxies include:

  • Not returning a value from traps like get, which causes undefined results.
  • Forgetting to handle all necessary traps for your use case.
  • Using proxies on non-objects (like primitives), which will throw errors.

Always ensure your traps return appropriate values and handle errors gracefully.

javascript
const target = { name: 'Alice' };

const handlerWrong = {
  get(obj, prop) {
    console.log(`Accessing ${prop}`);
    // Missing return statement causes undefined
  }
};

const proxyWrong = new Proxy(target, handlerWrong);
console.log(proxyWrong.name); // undefined

// Correct way
const handlerRight = {
  get(obj, prop) {
    console.log(`Accessing ${prop}`);
    return obj[prop];
  }
};

const proxyRight = new Proxy(target, handlerRight);
console.log(proxyRight.name); // Alice
Output
Accessing name undefined Accessing name Alice
📊

Quick Reference

TrapDescription
getIntercepts property access
setIntercepts property assignment
hasIntercepts the 'in' operator
deletePropertyIntercepts property deletion
applyIntercepts function calls
constructIntercepts object construction with 'new'

Key Takeaways

Use the Proxy constructor with a target object and a handler object to create a proxy.
Handler traps like 'get' and 'set' let you customize how properties are accessed or changed.
Always return values from traps to avoid unexpected undefined results.
Proxies only work on objects, not on primitive values like strings or numbers.
Common traps include 'get', 'set', 'has', 'deleteProperty', 'apply', and 'construct'.