Checkout my Getting Started with React video course on Skillshare. It is 100% free.

What are Javascript proxies?

We can see Javascript proxies as an extra layer we can add on top of an object, that allows us to add extra customization to that object.

Creating a javascript proxy is pretty straightforward:

let initialObject = { /* some plain object here */ };
let handler = { /* handler implementation here */ };
let proxyedObject = new Proxy(initialObject, handler);

Now, when we call something from the proxyedObject it will first search in the 'handler' for that something, and only if it does not find it there it will search into initialObject. Kind of how things worked with methods overloading in object-oriented programing.

For example, we can use a proxy to return a default message if we try to retrieve a value that was not defined in an object. For this, we will proxy the getters of that object.

let dog = {
  name: "Spike"

const handler = {
    get: (obj, property) => property in obj ? obj[property] : 'You don't have defined  a property named ' +  property;

const proxyDog = new Proxy(dog, handler);
// will print out Spike
// You don't have defined  a property named age

In the above case the get: (obj, property) => ... method is called a trap.

Let's see one more example, this time with a setter. We want to block assigning an age that is not within a valid range.

let dog = {
    name: "Spike",
    age: 1;
let handler = { 
    set: (obj, property, value) => { 
        if (property === 'age') { 
            if (!Number.isInteger(value)) throw new TypeError('Use numbers only for age'); 
            if ((value < 0) || (value > 30))  throw new RangeError('A dog can't live that long'); 
        obj[prop] = value; 
        return true; 

const proxyDog = new Proxy(dog, handler);
proxyDog.age = -1;
// will throw A dog can't live that long
proxyDog.age = 'very old';
// will throw Use numbers only for age

Using the Javascript proxy we can override not just setters and getters but also other methods like: deleteProperty, construct (the new operator), getOwnPropertyDescriptor etc.

PS: I've wrote more about usecases of Javascript proxies also here.

Home Screencasts Best of Newsletter Search X