DEV Community

Cover image for JavaScript Proxy a first introduction
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

JavaScript Proxy a first introduction

Recently I had my first production use-case for the Proxy object. So let me tell you a bit more about it and how you can use it in your code.

A Proxy object is a method that copies an object and can apply overwrites to specific functions.

This is a great way to intercept essential object functions like get or set.

JavaScript Proxy object

Let's start with a basic object definition.

const user = {
  firstName: 'Chris',
  lastName: 'Bongers',
  age: 10,
};
Enter fullscreen mode Exit fullscreen mode

Now, let's proxy this object.

const proxyUser = new Proxy(user, handler);
Enter fullscreen mode Exit fullscreen mode

The Proxy object takes two arguments, the first one is the original object and the second one is a handler. The handler defines which operations will be intercepted or modified.

Let's say we want to modify the get function.

const handler = {
  get(target, prop) {
    console.log('get called', target, prop);
    return target[prop].toUpperCase();
  },
};
Enter fullscreen mode Exit fullscreen mode

In the above example, we log what is being called and modify the get always to return an uppercase variant.

Let's now try to get the first name of the person.

console.log(proxyUser.firstName);
console.log(proxyUser.lastName);

// Returns: CHRIS BONGERS
Enter fullscreen mode Exit fullscreen mode

Pretty neat!

Let's quickly take a closer look at the variables we received.
The target holds the entire object, and the prop has the one that is being changed.

You can also only act on specific properties.

const handler = {
  get(target, prop) {
    if (prop === 'firstName') {
      return target[prop].toUpperCase();
    }
    return target[prop];
  },
};

console.log(proxyUser.firstName);
console.log(proxyUser.lastName);

// Returns: CHRIS Bongers
Enter fullscreen mode Exit fullscreen mode

In this case, only the firstName property will be returned in uppercase.

Type of handlers

We have seen the get handler being used, but there are more handlers we can leverage.

These handlers are often called traps, as they trap calls to the target object.

Here is a list of the traps we can overwrite.

  • apply
  • construct
  • deleteProperty
  • defineProperty
  • enumerate
  • get
  • getPrototypeOf
  • getOwnPropertyDescriptor
  • has
  • isExtensible
  • ownKeys
  • preventExtensions
  • set
  • setPrototypeOf

Each handler comes with its own set of properties. You can find the complete list on MDN.

MDN trap list

You can also try out the sample I prepared in this CodePen.

Conclusion

We can use the Proxy object to overwrite or catch specific object actions.

By using proxies, we can leverage some normally inaccessible handlers. These handlers can then be applied to all or some of the properties of an object.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (5)

Collapse
 
brense profile image
Rense Bakker

This reminds me if adapter pattern from OOP.

Collapse
 
peerreynders profile image
peerreynders

Proxy Pattern


Design Patterns: Elements of Reusable Object-Oriented Software (1995)

  • Adapter - Intent: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. (p.139)

  • Proxy - Intent: Provide a surrogate or placeholder for another object to control access to it. (p.207)

Collapse
 
dailydevtips1 profile image
Chris Bongers

Thanks for sharing these additional resources Peer.
Love that patterns.dev website actually! (First time seeing that ๐Ÿคฏ)

Collapse
 
omarbenmegdoul profile image
Omar Benmegdoul

What was the use case?

Collapse
 
dailydevtips1 profile image
Chris Bongers

Hey Omar,

Really good question and most of the time you won't need Proxy.
Here is one recent use-case where I needed it for:
daily-dev-tips.com/posts/javascrip...

As you can see super specific. ๐Ÿคฏ