Proxy Object in JavaScript
So I was surfing a internet and found somethings new topic i haven’t used .So let get going .
What is Proxy objects ?
In simple term is an object that can be used in place of the original object. This can include operation such as property lookup , assignment, enumeration and so on . It is especially useful for creating libraries , framework and advance patterns like data binding and validation.
How to use a proxy ?
Since proxy is created using the proxy constructor . So usually it takes two arguments i.e Target and Handler
1. Target : The object you want to proxy.
2. Handler : An object that defines which operations to intercept and how to redefine them.
So lets talk about the basic usage:
const target = {
message: "Hello, world!"
};
const handler = {
get(target, prop, receiver) {
console.log(`Getting ${prop}`);
return prop in target ? target[prop] : `Property ${prop} does not exist`;
},
set(target, prop, value) {
console.log(`Setting ${prop} to ${value}`);
target[prop] = value;
return true; // Indicate that the assignment was successful
}
};
const proxy = new Proxy(target, handler);
console.log(proxy.message); // Logs "Getting message" and "Hello, world!"
proxy.message = "Hello, Proxy!"; // Logs "Setting message to Hello, Proxy!"
console.log(proxy.message); // Logs "Getting message" and "Hello, Proxy!"So above was a basic example and i have listed some real world example where proxy object can be really helpful
- Validation:
You can use proxies to validate data before it is set on an object. For example, let’s create a proxy that ensures properties are strings and that their length does not exceed a certain limit:
const validator = {
set(target, prop, value) {
if (typeof value !== 'string') {
throw new TypeError('Value must be a string');
}
if (value.length > 10) {
throw new RangeError('Value length must not exceed 10 characters');
}
target[prop] = value;
return true;
}
};
const user = new Proxy({}, validator);
user.name = 'Alice'; // Works fine
console.log(user.name);
user.name = 'This name is too long'; // Throws RangeError: Value length must not exceed 10 characters2. Logging and Debugging
Get bishwa jung shah’s stories in your inbox
Join Medium for free to get updates from this writer.
Proxies can be used to automatically log interactions with an object, which can be useful for debugging or monitoring:
const logHandler = {
get(target, prop, receiver) {
console.log(`Getting ${prop}`);
return Reflect.get(...arguments);
},
set(target, prop, value) {
console.log(`Setting ${prop} to ${value}`);
return Reflect.set(...arguments);
}
};
const loggedObject = new Proxy({}, logHandler);
loggedObject.a = 1; // Logs: Setting a to 1
console.log(loggedObject.a); // Logs: Getting a3. Data binding
In frameworks like Vue.js, proxies are used to create reactive data bindings. Here’s a simplified example of how you might use a proxy for such a purpose:
function createReactiveObject(target, onChange) {
return new Proxy(target, {
set(target, prop, value) {
const result = Reflect.set(target, prop, value);
onChange(prop, value);
return result;
}
});
}
const state = createReactiveObject({ count: 0 }, (prop, value) => {
console.log(`Property ${prop} changed to ${value}`);
});
state.count = 1; // Logs: Property count changed to 14. Mocking Objects for Testing
Proxies can be useful for creating mocks in tests. For example, you might use a proxy to simulate a complex API response:
const apiMock = new Proxy({}, {
get(target, prop) {
if (prop === 'fetchData') {
return () => Promise.resolve({ data: 'mocked data' });
}
return () => Promise.reject(new Error('Not implemented'));
}
});
apiMock.fetchData().then(response => console.log(response.data)); // Output: mocked dataSo above was some of the real world scenario where you can you the proxy object .
you can check more here








