Back

/ 2 min read

JavaScript Proxy: A Powerful Metaprogramming Feature

JavaScript Proxy is a metaprogramming feature that allows you to intercept and customize operations on objects. In this article, you’ll learn how to use Proxy to create powerful abstractions, implement data validation, and more.

What is JavaScript Proxy?

A Proxy object wraps another object and intercepts operations, like property lookup, assignment, invocation, etc. You can customize the behavior of these operations by providing handler functions.

Here’s a simple example that logs property access:

const target = { name: 'Alice' };
const handler = {
get(target, prop, receiver) {
console.log(`Getting property ${prop}`);
return Reflect.get(target, prop, receiver);
},
};
const proxy = new Proxy(target, handler);
console.log(proxy.name); // Logs: Getting property name

In this example, the handler.get function logs a message before returning the property value. The Reflect.get function is used to forward the operation to the target object.

Creating Abstractions with Proxy

Proxy allows you to create powerful abstractions. For example, you can create a ReadOnly proxy that prevents modifications to an object:

function ReadOnly(obj) {
return new Proxy(obj, {
set() {
throw new Error('Cannot modify read-only object');
},
});
}
const user = ReadOnly({ name: 'Alice' });
user.name = 'Bob'; // Throws an error

In this example, the ReadOnly function returns a proxy that throws an error when a property is set. This prevents modifications to the original object.

Implementing Data Validation

Proxy can be used to implement data validation. For example, you can create a Validator proxy that validates property values:

function Validator(obj) {
return new Proxy(obj, {
set(target, prop, value) {
if (typeof value !== 'number') {
throw new Error('Value must be a number');
}
return Reflect.set(target, prop, value);
},
});
}
const person = Validator({ age: 30 });
person.age = 40; // OK
person.age = '40'; // Throws an error

In this example, the Validator function returns a proxy that checks if the value is a number before setting the property.

Conclusion

JavaScript Proxy is a powerful metaprogramming feature that allows you to intercept and customize operations on objects. You can use Proxy to create powerful abstractions, implement data validation, and more. I hope this article helps you understand the power of Proxy and how you can use it in your projects.