šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

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);
console.log(proxyDog.name);
// will print out Spike
console.log(proxyDog.age);
// 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[property ] = 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 and about how to work with Javascript proxies, private fields and the Reflect API.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *