Today I Learned - Rocky Kev

TIL ES6 Proxy

POSTED ON:

TAGS:

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:

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.

MDN

via Svetloslav Novoselski's What are ES6 Proxies and how to use them? and JavaScript Proxy


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.