Skip to content

How Do Proxy Objects Work in JavaScript?

A JavaScript proxy object enables you to intercept and customise the conduct of one other object, with out modifying the unique.


Utilizing proxy objects, you may validate information, present additional performance, and management entry to properties and capabilities.

Discover out all concerning the makes use of of proxy objects and how one can create them in JavaScript.


Making a Proxy Object

In JavaScript, you may create proxy objects utilizing the proxy builder. This constructor takes two arguments: a goal object to wrap the proxy round and a handler object whose properties outline the proxy’s conduct if you perform operations.

It takes these arguments and creates an object you should use rather than the goal object. This created object can redefine core operations reminiscent of getting, setting, and defining properties. You can too use these proxy objects to log property accesses and validate, format, or sanitize inputs.

For instance:

 const originalObject = {
  foo: "bar"
}

const handler = {
  get: perform(goal, property) {
    return goal[property];
  },
  set: perform(goal, property, worth) {
    goal[property] = worth;
  }
};

const proxy = new Proxy(originalObject, handler)

This code creates a goal object, originalObjectwith a single property, fooand a handler object, handler. The handler object incorporates two properties, get and set. These properties are referred to as traps.

A proxy object entice is a perform referred to as everytime you carry out a specified motion on a proxy object. Traps mean you can intercept and customise the conduct of the proxy object. Accessing a property from the proxy object calls the get entice, and modifying or manipulating a property from the proxy object calls the set entice.

Lastly, the code creates a proxy object with the proxy builder. it passes originalObject and handler because the goal object and handler, respectively.

Utilizing Proxy Objects

Proxy objects have a number of makes use of in JavaScript, a few of that are as follows.

Including Performance to an Object

You should use a proxy object to wrap an current object and add new performance, reminiscent of logging or error dealing with, with out modifying the unique object.

So as to add new performance, you will want to make use of the proxy constructor and outline a number of traps for the actions you need to intercept.

For instance:

 const userObject = {
  firstName: "Kennedy",
  lastName: "Martins",
  age: 20,
};

const handler = {
  get: perform (goal, property) {
    console.log(`Getting property "${property}"`);
    return goal[property];
  },
  set: perform (goal, property, worth) {
    console.log(`Setting property "${property}" to worth "${worth}"`);
    goal[property] = worth;
  },
};

const proxy = new Proxy(userObject, handler);

console.log(proxy.firstName);
console.log(proxy.lastName);
proxy.age = 23; // Setting property "age" to worth "23"

This code block provides performance by way of the proxy traps, get and set. Now, if you attempt to entry or modify a property of the userObjectthe proxy object will first log your operation to the console earlier than accessing or modifying the property.

Validating Information Earlier than Setting It on an Object

You should use proxy objects to validate information and guarantee it meets sure standards earlier than setting it on an object. You are able to do so by defining the validation logic in a set entice within the handler object.

For instance:

 const userObject = {
  firstName: "Kennedy",
  lastName: "Martins",
  age: 20,
};

const handler = {
  get: perform (goal, property) {
    console.log(`Getting property "${property}"`);
    return goal[property];
  },
  set: perform (goal, property, worth) {
    if (
      property === "age" &&
      typeof worth == "quantity" &&
      worth > 0 &&
      worth < 120
    ) {
      console.log(`Setting property "${property}" to worth "${worth}"`);
      goal[property] = worth;
    } else {
      throw new Error("Invalid parameter. Please evaluate and proper.");
    }
  },
};

const proxy = new Proxy(userObject, handler);
proxy.age = 21;

This code block provides validation guidelines to the set entice. You may assign any worth to the age property on a userObject occasion. However, with the added validation guidelines, you may solely assign a brand new worth to the age property if it is a quantity, larger than 0, and fewer than 120. Any worth you attempt to set on the age property that doesn’t meet the required standards will set off an error and print an error message.

Controlling Entry to Object Properties

You should use proxy objects to cover sure properties of an object. Accomplish that by defining restriction logic in get traps for the properties you need to management entry to.

For instance:

 const userObject = {
  firstName: "Kennedy",
  lastName: "Martins",
  age: 20,
  cellphone: 1234567890,
  electronic mail: "foo@bar.com",
};

const handler = {
  get: perform (goal, property) {
    if (property === "cellphone" || property === "electronic mail") {
      throw new Error("Entry to data denied");
    } else {
      console.log(`Getting property "${property}"`);
      return goal[property];
    }
  },
  set: perform (goal, property, worth) {
    console.log(`Setting property "${property}" to worth "${worth}"`);
    goal[property] = worth;
  },
};

const proxy = new Proxy(userObject, handler);

console.log(proxy.firstName);
console.log(proxy.electronic mail);

The code block above provides sure restrictions to the get entice. Initially, you may entry all obtainable properties on userObject. The added guidelines forestall entry to delicate info such because the person’s electronic mail or cellphone. Attempting to entry both of those properties will set off an error.

Different Proxy Traps

The get and set Traps are the commonest and helpful, however there are 11 different JavaScript proxy traps. They’re:

  • apply: The apply entice runs if you name a perform on the proxy object.
  • construct: The construct entice runs if you use the brand new operator to create an object from the proxy object.
  • deleteProperty: The deleteProperty entice runs if you use the delete operator to take away a property from the proxy object.
  • have you ever -The have you ever entice runs if you use the in operator to test if a property exists on the proxy object.
  • ownKeys -The ownKeys entice runs if you name both the Object.getOwnPropertyNames or Object.getOwnPropertySymbols perform on the proxy object.
  • getOwnPropertyDescriptor -The getOwnPropertyDescriptor entice runs if you name the Object.getOwnPropertyDescriptor perform on the proxy object.
  • defineProperty -The defineProperty entice runs if you name the Object.defineProperty perform on the proxy object.
  • preventExtensions -The preventExtensions entice runs if you name the Object.preventExtensions perform on the proxy object.
  • isExtensible -The isExtensible entice runs if you name the object.isExtensible perform on the proxy object.
  • getPrototypeOf -The getPrototypeOf entice runs if you name the Object.getPrototypeOf perform on the proxy object.
  • setPrototypeOf -The setPrototypeOf entice runs if you name the Object.setPrototypeOf perform on the proxy object.

just like the set and get traps, you should use these traps can so as to add new layers of performance, validation, and management to your object with out modifying the unique.

The Cons of Proxy Objects

Proxy objects generally is a highly effective instrument for including customized performance or validation to an object. However additionally they have some potential drawbacks. One such disadvantage is tough to debug, as it may be arduous to see what’s taking place behind the scenes.

Proxy objects can be tough to make use of, particularly if you’re unfamiliar with them. You need to rigorously think about these drawbacks earlier than utilizing proxy objects in your code.

Leave a Reply

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