Created
February 16, 2020 23:24
-
-
Save iainjreid/14075d3afb9864153d7344bf5a8f6557 to your computer and use it in GitHub Desktop.
Protecting properties using a JavaScript Proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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