— Javascript, Proxy — 1 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:
Go out there and build!