Today I Learned - Rocky Kev

TIL ES6 Proxy's apply method

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.

So if you wanted to create a proxy of getFullName...

const user = {
firstName: 'John',
lastName: 'Doe'
}

const getFullName = function (user) {
return `${user.firstName} ${user.lastName}`;
}


const getFullNameProxy = new Proxy(getFullName, {
apply(target, thisArg, args) {
return target(...args).toUpperCase();
}
});

console.log(getFullNameProxy(user)); // JOHN DOE

This mutates the result!

What's a good use case?

function sum(a, b) {
return a + b;
}

const handler = {
apply: function(target, thisArg, argumentsList) {
console.log(`Calculate sum: ${argumentsList}`);
// expected output: "Calculate sum: 1,2"

return target(argumentsList[0], argumentsList[1]) * 10;
}
};

const sumTriple = new Proxy(sum, handler);

console.log(sum(1, 2));
// expected output: 3
console.log(sumTriple(1, 2));
// expected output: 30

Now you can keep the sum function AND a unique version, like sumTriple!

MDN

MDN for handler.apply()


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.