TIL ES6 Proxy
POSTED ON:
TAGS: javascript mdn advanced codepen
Using JavaScript proxies you can wrap an existing object and intercept access to its attributes or methods, even if they don’t exist. You can also redefine fundamental operations for that object.
There's two main terms to remember:
- Target — is the original object you want to wrap. It can be everything, also function.
- Handler — is an object which define methods that intercept operations. These methods are also called “traps”.
To use a simple example:
const dictionary = {
apple: 'pomme',
peach: 'pêche',
orange: 'orange'
};
const handler = {
get: (target, prop) => {
return target[prop] || 'This word is not translated yet';
},
set: (target, prop, val) => {
if (typeof val === 'string') {
target[prop] = val;
}
}
};
const proxy = new Proxy(dictionary, handler);
console.log(proxy['peach']); // pêche
console.log(proxy['grapes']); // This word is not translated yet
proxy['grapes'] = 5
console.log(proxy['grapes']); // This word is not translated yet
proxy['grapes'] = 'grain de raisin';
console.log(proxy['grapes']); // grain de raisin
So when you access the proxy, it gets sent into the get()
method.
When you want to save something to the object, it runs through the set()
method.
Here's another example:
const user = {
firstName: 'John',
lastName: 'Doe',
age: 20
}
const userHandler = {
get: (target, property) => {
return property === 'fullName' ?
`${target.firstName} ${target.lastName}` : target[property];
},
set: (target, property, value) => {
if (property === 'age') {
if (typeof value !== 'number') {
throw new Error('Age must be a number.');
}
if (value < 18) {
throw new Error('The user must be 18 or older.')
}
}
target[property] = value;
}
};
const proxyUser = new Proxy(user, userHandler);
console.log(proxyUser.fullName); // John Doe
proxyUser.age = 'dog'; // uncaught error: age must be a number
proxyUser.age = 12; // uncaught error: the user must be 18 or older
proxyUser.age = 20; // uncaught error: the user must be 18 or older
console.log(proxyUser.age); // 20
See the Pen JS proxies by rockykev (@rockykev) on CodePen.
via Svetloslav Novoselski's What are ES6 Proxies and how to use them? and JavaScript Proxy
Related TILs
Tagged: javascript