Proxies & Reflect
We'll cover the following...
A Proxy in ES6 is a special type of object that allows us to intercept operations preformed on an Object. Operations like property lookups, assignments and more. Proxies all us to set up a target
object with a handler
. The handler
object is used to override the operations on our target object. Let’s first look at the syntax for our Proxy.
new Proxy(target,handler);
With this in mind, let’s create a person
object with two simple properties on it.
const person = new Proxy({name: 'Ryan',age: 31},{//Handler goes here.})
On this person
object, we have only two properties name
and age
. The handler
object is used to list ‘traps’, these trap methods include get()
, set()
, and much more. As an example, lets set up a Proxy that has a get
trap.
const person = new Proxy({name: 'Ryan',age: 31}, {get(target, prop) {return target[prop]}});
Here we implement a get
trap on our handler, notice that the method gets passed two arguments, target
, and prop
. target
is the object we are trying to access the property from. And prop
is what key
we want to access. Calling person.name
will trigger the get
trap, as we are trying to access the name
property. In our trap here we simply return the value, but image that we could alter the values.
Let’s change this to return all uppercase strings from our object.
const person = new Proxy({name: 'Ryan',age: 31}, {get(target, prop) {const val = target[prop];return typeof val === 'string' ? val.toUpperCase() : val;}});console.log(person.name); //RYAN
This opens up a ...