Skip to content

Instantly share code, notes, and snippets.

@mrenty
Created December 31, 2017 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrenty/f90d9ae08318d8bc6b87b88f0a07062f to your computer and use it in GitHub Desktop.
Save mrenty/f90d9ae08318d8bc6b87b88f0a07062f to your computer and use it in GitHub Desktop.
Javascript Proxy Objects
const handler = {
get: function(obj, prop) {
if (prop === 'id') { // Check if the id is being accessed
throw new Error('Cannot access private properties!'); // Throw an error
} else {
return obj[prop]; // If it's not the id property, return it as usual
}
}
}
const person = {
id: 1,
name: 'Foo Bar'
}
const proxiedPerson = new Proxy(person, handler);
console.log(proxiedPerson.id);
const handler = {
set: function(obj, prop, value) {
if (typeof value !== 'string') {
throw new Error('Only string values can be stored in this object!');
} else {
obj[prop] = value;
}
}
}
const obj = {};
const proxiedObj = new Proxy(obj, handler);
console.log(proxiedObj); // This will log an empty object
proxiedObj.name = 'Foo Bar'; // This should be allowed
console.log(proxiedObj); // This will log an object with the name property set
proxiedObj.age = 24; // This will throw an error.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment