DEV Community

Quan Nguyen
Quan Nguyen

Posted on

What is Proxy in javascript ?

The Proxy in JavaScript is a feature that allows you to intercept and modify operations performed on an object. It is created using the Proxy constructor and takes two parameters: the target object and an object that defines the behavior of the proxy. The behavior of the proxy is defined through a set of trap methods, which are called whenever an operation is performed on the target object.

One of the most common use cases of the Proxy object is to implement custom behavior for property access. For example, you can use the get trap to log all property access, or the set trap to validate property values before they are set.

Here's an example of a Proxy that logs all property access:

const target = {};
const handler = {
  get: (target, property) => {
    console.log(`Accessing property: ${property}`);
    return target[property];
  },
};
const proxy = new Proxy(target, handler);

proxy.name = "John Doe";
console.log(proxy.name);
Enter fullscreen mode Exit fullscreen mode

In this example, the handler object provides a get trap method that logs all property access. Whenever a property is accessed on the proxy object, the get trap is called, and it logs the access to the console.

Another use case of the Proxy object is to add or modify properties on the target object. For example, you can use the get trap to add computed properties that are derived from other properties, or the set trap to override properties on the target object.
Here's an example of a Proxy that adds a computed property:

const target = {};
const handler = {
  get: (target, property) => {
    if (property === "fullName") {
      return `${target.firstName} ${target.lastName}`;
    }
    return target[property];
  },
};
const proxy = new Proxy(target, handler);

proxy.firstName = "John";
proxy.lastName = "Doe";
console.log(proxy.fullName);

Enter fullscreen mode Exit fullscreen mode

In this example, the handler object provides a get trap method that adds a computed property fullName that is derived from the firstName and lastName properties. When the fullName property is accessed, the get trap is called, and it returns the concatenation of the firstName and lastName properties.

In conclusion, the Proxy in JavaScript is a powerful and versatile tool that can be used to implement custom behavior for property access, add or modify properties, and control the access to certain properties. Whether you are writing a large-scale web application or a simple utility, the Proxy object provides a flexible and efficient way to control the behavior of your objects.

Top comments (0)