5

What are Javascript proxies?

 2 years ago
source link: http://www.js-craft.io/blog/what-are-javascript-proxies/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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[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.

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.

Newsletter subscribe:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK