Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Created July 14, 2024 03:43
Show Gist options
  • Save kevboutin/ec2b255e6b7843308d4b4a5f3581b207 to your computer and use it in GitHub Desktop.
Save kevboutin/ec2b255e6b7843308d4b4a5f3581b207 to your computer and use it in GitHub Desktop.
Enforce type constraints and log access attempts
/* The Proxy object allows you to create a proxy for another object,
* enabling you to intercept and redefine fundamental operations such
* as property lookup, assignment, enumeration, function invocation,
* etc. This provides a powerful way to add custom behavior to objects.
*/
const user = {
name: 'John',
age: 30
};
const handler = {
get: (target, prop) => {
console.log(`Getting ${prop}`);
return target[prop];
},
set: (target, prop, value) => {
if (prop === 'age' && typeof value !== 'number') {
throw new TypeError('Age must be a number');
}
console.log(`Setting ${prop} to ${value}`);
target[prop] = value;
return true;
}
};
const proxyUser = new Proxy(user, handler);
console.log(proxyUser.name); // Getting name, John
proxyUser.age = 35; // Setting age to 35
// proxyUser.age = '35'; // Throws TypeError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment