Logging Property Access with Proxies
Demonstrate using a Proxy to log each access to property reads on an object for debugging purposes.
// Create an object that we will monitor
const targetObject = {
name: 'Proxy Target',
value: 42
};
// Define the handler to log property access
const logHandler = {
get(target, property, receiver) {
console.log(`Accessing property '${property}'`);
return Reflect.get(target, property, receiver);
}
};
// Create the proxy to add the logging behavior
const proxyObject = new Proxy(targetObject, logHandler);
// Access properties through the proxy to trigger the logging
console.log(proxyObject.name); // Logs: Accessing property 'name'
console.log(proxyObject.value); // Logs: Accessing property 'value'
Create a proxy to log access to property reads on an object for debugging. The 'logHandler' defines a 'get' trap that logs each access, and the 'proxyObject' uses this handler. Access properties on 'proxyObject' to see logs.