Sitemap

Proxy Object

5 min readMar 27, 2024

--

In modern front-end frameworks, the Proxy object plays a pivotal role, providing developers with a more flexible and powerful way to manage and manipulate JavaScript objects.

What is a Proxy Object?

A Proxy object offers a mechanism to customize the behavior of fundamental operations (like property lookup, assignment, enumeration, etc.) on objects. It works by setting up an interception layer in front of a target object, meaning any access to that object must first pass through this interception. This capability allows developers to inject additional behaviors or rules before or after the operation execution.

The Relationship Between Proxy and Reflect Objects

Reflect is a global object that provides a set of static methods corresponding to all interceptable operations by Proxy traps. These methods ensure the default behavior of operations while being used together with Proxy, facilitating the extension and control of object behaviors with convenience and predictability.

For Example:

let profile = {
firstName: "Micky",
lastName: "Mouse"
};

let proxy = new Proxy(profile, {
get: function (target, property) {
if (property === "wholeName") {
return target.lastName + target.firstName
} else {
return target[property]
}
},
})

can do like this:

let profile = {
firstName: "Micky",
lastName: "Mouse"
};

let proxy = new Proxy(profile, {
get: function(target, property, receiver) {
if (property === "wholeName") {
return target.lastName + target.firstName;
} else {
return Reflect.get(...arguments);
}
}
});

What are Handler and Trap in a Proxy Object?

A handler is an object that contains interceptor functions, which define custom behavior for various operations; these functions are known as traps. For example, a get trap can intercept the operation of reading a property of an object, while a set trap is used to intercept the operation of assigning a value to a property of an object.

For Example:

const handler = {
get: function(target, property) {
if (property in target) {
return target[property];
}
return `Property ${property} not found`;
},
set: function(target, property, value) {
console.log(`Setting value ${value} to ${property}`);
target[property] = value;
return true;
}
};

const proxy = new Proxy({}, handler);
proxy.a = 1; // Console output: Setting value 1 to a
console.log(proxy.a); // 1
console.log(proxy.b); // Property b not found

Implementing Virtual Properties with Proxy

To utilize a Proxy for creating virtual properties on an object, you can customize the behavior for accessing properties that do not exist on the target object directly. Through the use of a Proxy’s get trap, when an attempt is made to access a non-existent property, you can return a predefined value or execute specific logic.

For Example:

let profile = {
firstName: "Micky",
lastName: "Mouse"
};

let proxy = new Proxy(profile, {
get: function(target, property, receiver) {
if (property === "wholeName") {
// Defines a virtual property that combines lastName and firstName
return `${target.lastName} ${target.firstName}`;
} else {
// For existing properties, the default behavior is preserved
return Reflect.get(...arguments);
}
}
});

In this scenario, the profile object doesn't initially have a wholeName property. However, by utilizing a Proxy, when you access proxy.wholeName, the get trap is activated. It checks if the accessed property is wholeName, and if so, it dynamically constructs the value by concatenating lastName and firstName from the target object. For any other property access, it falls back to the default behavior by using Reflect.get, ensuring that normal property accesses are unaffected by the Proxy.

Differences Between Proxy Objects and Object.defineProperty

While Object.defineProperty allows for precise control over individual property descriptors (like enumerability, configurability, etc.), it's limited to existing properties' manipulation. In contrast, Proxy offers comprehensive control over objects, not just managing individual properties but intercepting object-level operations like property access, assignment, iteration, and more. Proxy's dynamic and flexible nature far exceeds the capabilities of Object.defineProperty, enabling runtime behavior changes as needed.

Implementing Deep Observation with Proxy

Deep observation of objects can be achieved using Proxy by recursively proxying all properties of the target object, including nested properties, within the Proxy’s handler. This approach allows for intercepting reads and modifications to any property, enabling deep monitoring of changes to the object.

Get Just code every day’s stories in your inbox

Join Medium for free to get updates from this writer.

For Example:

function deepObserver(target) {
const handler = {
get(target, property, receiver) {
try {
return new Proxy(target[property], handler);
} catch (err) {
return Reflect.get(target, property, receiver);
}
},
set(target, property, value) {
console.log(`${property} set to ${value}`);
target[property] = value;
return true;
}
};
return new Proxy(target, handler);
}

const observedObject = deepObserver({a: 1, b: {c: 2}});
observedObject.b.c = 3; // Console output: c set to 3

The Infinite Recursion Issue with Proxy

Consider a situation where we have an object that contains a reference to itself:

const obj = {
self: null
};
obj.self = obj;

If we attempt to use a Proxy to observe this object and print a message each time a property is accessed, we might write something like this:

const handler = {
get(target, property, receiver) {
console.log(`Accessing property: ${property}`);
return new Proxy(target[property], handler); // Attempt to create a new proxy for each property
}
};

const proxy = new Proxy(obj, handler);
console.log(proxy.self);

This approach leads to a problem because when we try to access proxy.self, the get trap is triggered and attempts to create a new proxy for obj.self (which is obj itself). This triggers the get trap again, attempting to create another new proxy for this already proxied object, thus forming an infinite loop and causing infinite recursion.

How to Avoid Infinite Recursion

To address this issue, we can use a WeakMap to keep track of objects that have already been proxied, ensuring that each object is only proxied once:

const handler = {
get(target, property, receiver) {
console.log(`Accessing property: ${property}`);
const value = target[property];
if (typeof value === 'object' && value !== null) {
if (!proxiedObjects.has(value)) {
const proxy = new Proxy(value, handler);
proxiedObjects.set(value, proxy); // Record this object's proxy in the WeakMap
return proxy;
} else {
return proxiedObjects.get(value); // Return the existing proxy
}
}
return value;
}
};

const proxiedObjects = new WeakMap(); // A WeakMap to track proxied objects
const proxy = new Proxy(obj, handler);

In this solution, we first check whether the currently accessed object already has a proxy stored in the WeakMap. If not, we create a new proxy and store it; if it does, we directly return the existing proxy. This approach prevents infinite recursion, even in the presence of self-referencing properties, by ensuring each object is only proxied once.

Performance Considerations When Using Proxy

Using Proxy objects in the applications comes with certain performance considerations. While Proxy offers powerful capabilities to intercept and customize the behavior of object operations, it may introduce overhead compared to direct object access, especially in performance-critical applications. Here are some scenarios :

  1. High-frequency operations: If a Proxy object is used in a part of the application where operations are performed very frequently, the additional processing required by the Proxy traps can impact performance. For example, using a Proxy to intercept array manipulations in a tight loop may slow down execution.
  2. Deeply nested objects: Implementing deep observation patterns with Proxy, where you create new Proxy instances for nested objects dynamically, can add significant overhead due to the creation of multiple Proxy objects and the recursive nature of the operation.
  3. Large objects: Using Proxy to monitor access to very large objects or arrays can also lead to performance degradation. Each access or modification triggers the Proxy’s traps, which can become costly if the object is large and operations are numerous.

To mitigate potential performance issues, consider the following strategies:

  • Limit the use of Proxy to objects where the benefits of behavior customization or observation outweigh the potential performance costs.
  • Avoid using Proxy in performance-critical code paths, or benchmark the application to understand the impact.
  • Use Proxy selectively, applying it only to parts of an object’s structure that truly require it, rather than applying it indiscriminately to all objects and properties.

--

--

Just code every day
Just code every day

Written by Just code every day

Code to learn, learn through code.