Skip to content

Instantly share code, notes, and snippets.

@iainjreid
Created February 16, 2020 23:24
Show Gist options
  • Save iainjreid/14075d3afb9864153d7344bf5a8f6557 to your computer and use it in GitHub Desktop.
Save iainjreid/14075d3afb9864153d7344bf5a8f6557 to your computer and use it in GitHub Desktop.
Protecting properties using a JavaScript Proxy
const dog = {
breed: 'Labrador',
name: 'Jed',
age: 7
};
const dogCopy = protectProperties(dog);
dog.breed = 'Poodle'; // Success - We've now got a Poodle
dogCopy.breed = 'Beagle'; // Error - This object is protected
function protectProperties(target) {
return new Proxy(target, {
set() {
throw Error('This object is protected');
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment