Blog: https://dev.to/marclipovsky/discovering-the-power-of-javascript-proxy-after-all-this-time-4627
Lazy loading:
const lazyLoadHandler = {
get: function (target, property) {
if (!target[property]) {
target[property] = expensiveComputation();
}
return target[property];
},
};
const lazyLoadedObject = new Proxy({}, lazyLoadHandler);
const result = lazyLoadedObject.expensiveProperty; // Calls expensiveComputation() on first access
Readonly:
const readOnlyHandler = {
set: function (target, property, value) {
if (property === 'readOnly') {
throw new Error('Cannot modify read-only property');
}
target[property] = value;
return true;
},
};
const protectedObject = new Proxy({ readOnly: true }, readOnlyHandler);
protectedObject.newProperty = 'some value'; // OK
protectedObject.readOnly = false; // Throws Error
标签:const,target,Javascript,protectedObject,Proxy,new,property,Snippets From: https://www.cnblogs.com/Answer1215/p/17370999.html