Proxies
Proxies allow you to overwrite the default behavior of certain operations such as get, set, etc. called ‘traps’. We can intercept certain functions and alter their default behavior using proxies.
const person = {name:’AK’, age: 26};
First it takes a target, which is what object you would like to proxy
Second, a handler which contains all the operations you wish to rewrite
const personProxy = new Proxy(person, {
get(target, name){
console.log(“Someone is requesting”, target, name);
return target[name].toUpperCase();
});
set(target, name,value){
if(typeof value === ‘string’) {
target[name] = value.trim().toLowerCase();
}
}
personProxy.name = “Arjun”; //setter saves lowercase trimmed value
personProxy.name; //getter returns uppercase Arjun
No comments:
Post a Comment