javascriptes6-proxy

Major use cases for ES6 proxies


I recently got to know about ES6 proxies but I don't see a good reason to use it. I mean, everything that one could do with Proxy can be done without it, except if I'm missing something.

For example, most folks talk about validation when it comes to proxy but one could apply some JS goodness to validate and everyone is fine. I would appreciate if someone could open my eyes to some major use cases of Proxies. Thanks!


Solution

  • I mean, every thing that one could do with Proxy can be done without it...

    If that were true, TC39 wouldn't have added Proxy. But in fact there are things you can't do without Proxy.

    Consider the common need to catch access to properties that don't exist:

    const o = { foo: "bar" };
    console.log(o.blarg);
    

    It's common to want to handle that in a way other than the default, which is for accessing o.blarg to result in undefined:

    const o = { foo: "bar" };
    console.log(`foo:   ${o.foo}`);
    console.log(`blarg: ${o.blarg}`);

    Proxy lets us do that, via the get trap. For example, you could throw an error:

    const o = { foo: "bar" };
    const p = new Proxy(o, {
        get(target, prop, receiver) {
            if (prop in target) {
                return target[prop];
            }
            throw new Error(`Property "${prop}" doesn't exist in object`);
        }
    });
    console.log(`foo:   ${p.foo}`);
    console.log(`blarg: ${p.blarg}`);

    Another example is the ability to hook into the various operations that get the list of properties on an object. There is no way to hook into that without Proxy. With Proxy, it's easy: You use the has trap or the ownKeys trap depending on what you want to hook into.

    In terms of other use cases: Proxy is the ultimate tool for implementing the Facade pattern. Look for the use cases of Facade, and you'll find use cases for Proxy.