Week 45: Understanding Proxy in JavaScript

We can use Proxy to create a proxy for another object in JavaScript. We can intercept and redefine the operations on the proxied object through a proxy object.


    const proxy = new Proxy(target, handler);

Proxy takes 2 parameter.

Setting an empty {} as a handler creates a no=ops proxy.


    const user = { name: 'john', age: 20 };

    const proxyUser = new Proxy(user, {}); // creates a no-ops proxy
    proxyUser.name; // john
    proxyUser.age; // 20

We can use also can redefine operations in the handler.


    const user = { name: 'john', age: 20 };

    const handler = {
        get(target, property) {
            if (!target[property]) {
              throw new Error(`'${property}' doesn't exist. Read the doc manual.`);
            }

            console.log(`Property '${property}' has been read.`);
            return target[property];
        }
    };

    const proxyUserWithLogs = new Proxy(user, handler);
    proxyUserWithLogs.name; // Property 'name' has been read.

Please note that private fields won't be accessible since the proxy create a different object.


    class User {
      #details = {
        firstName: "John",
        lastName: "Doe",
        email: "john.doe@example.com"
      };

      get details() {
        return this.#details;
      }
    }

    const user = new User();
    const userProxy = new Proxy(user, {});

    user.details.firstName; // Property 'details' has been read.
    userProxy.details.firstName; // TypeError: can't access private field or method: object is not the right class


For my new posts, Subscribe via weekly RSS, common RSS or Subscribe via Email