Skip to content
Turtle

Javascript Proxy

Javascript, Proxy1 min read

While browsing through some programming books, I came across Understainding ECMAScript 6 which had a cool section on Proxies. Proxies are objects which we can use to intercept operations on target objects. Below, we define a Proxy for an empty object where we override the setter.

1const target = {};
2const proxy = new Proxy(target, {
3 set: (obj, prop, value) => {
4 console.log(`Setting ${prop} to ${value}`)
5 obj[prop] = value;
6 }
7});

Now when we set a value on our proxy, our target will have that value and our log will be called:

1proxy.name = 'turtle'
2'Setting name to turtle'

Proxies are built using the Reflect API and can be used for validating getters/setters. The example below shows how we can throw an error if a property does not exist on the target.

1const target = {
2 name: 'hi',
3};
4const proxy = new Proxy(target, {
5 get: (target, prop, receiver) => {
6 if (prop in receiver) {
7 return Reflect.get(target, prop, receiver);
8 }
9 throw new Error('property does not exist!');
10 }
11});
12
13proxy.name // 'hi'
14proxy.dne // Uncaught Error: property does not exist!

Some use cases for proxies:

  • Validation: Is the input a valid integer?
  • Caching: Can we return the data from memory instead of fetching from our api?
  • Observability: Can we be notified when an object's state is changed?

Go out there and build!