I have read the documentation for Proxy and Reflect on MDN but didn't understand much. Can anyone please explain or mention the real world use of these ES6
features.
- One of the good use of proxy I found is that we can declare our object values as private -
const object = {
name: "Rajesh Royal",
Age: 23,
_Sex: "Male"
}
const logger = {
get(target, property){
if(property.startsWith("_")){
throw new Error(`${property} is a private property.`);
}
console.log(`Reading the property ${property}`);
return target[property];
}
}
const Logger = new Proxy(object, logger);
// now if you try to access the private property it will throw an error
Logger._Sex
Uncaught Error: _Sex is a private property.
at Object.get (<anonymous>:4:19)
at <anonymous>:1:8
well, hard to imagine a use case for that unless you're building your own framework or a library. If someone asks me such stuff in an interview, I would go 'cmon are you doing some rocket science'?)