TIL ES6 Proxy's apply method
POSTED ON:
TAGS: javascript mdn advanced
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!
Related TILs
Tagged: javascript