0 day streak
javascript / intermediate
Snippet

Metaprogramming with Proxies

The Proxy object allows you to create a wrapper for another object, which can intercept and redefine fundamental operations for that object, such as property lookup, assignment, and enumeration.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const user = {
firstName: 'Jonas',
lastName: 'Weber'
};
const handler = {
get: (target, prop) => {
if (prop === 'fullName') {
return `${target.firstName} ${target.lastName}`;
}
return prop in target ? target[prop] : 'Property not found';
}
};
const proxyUser = new Proxy(user, handler);
console.log(proxyUser.fullName); // Jonas Weber
console.log(proxyUser.age); // Property not found
Breakdown
1
const handler = { get: (target, prop) => { ... } };
Defines a 'trap' for getting property values.
2
const proxyUser = new Proxy(user, handler);
Creates the proxy by wrapping the original user object with the handler logic.