JSFiddle - React, Tailwind, and code Playground
JavaScript
const target = {
name: 'Alice',
age: 30,
}
const handler = {
get: function(target, prop, receiver) {
console.log(`Getting property ${prop}`);
return Reflect.get(target, prop, receiver);
},
set: function(target, prop, value, receiver) {
console.log(`Setting property ${prop} to ${value}`);
target[prop] = value;
return true;
},
has: function(target, prop) {
console.log(`Checking if property ${prop} is in target.`);
return prop in target;
},
deleteProperty: function(target, prop) {
console.log(`Deleting property ${prop}.`);
delete target[prop];
return true;
},
apply: function(target, thisArg, argumentsList) {
console.log(`Called with arguments: ${argumentsList}`);
return target.apply(thisArg, argumentsList);
},
ownKeys: function(target) {
console.log('Getting property keys.');
return Reflect.ownKeys(target);
}
};
const proxy = new Proxy(target, handler);
// Using get trap
console.log(proxy.name); // Logs: Getting property name. Output: Alice
// Using set trap
proxy.age = 35; // Logs: Setting property age to 35
console.log(target.age); // Output: 35
// Using has trap
console.log('name' in proxy); // Logs: Checking if property name is in target. Output: true
// Using deleteProperty trap
delete proxy.age; // Logs: Deleting property age.
console.log(target.age); // Output: undefined
// Using ownKeys trap
console.log(Object.keys(proxy)); // Logs: Getting property keys. Output: ['name']