-
-
Save mrenty/f90d9ae08318d8bc6b87b88f0a07062f to your computer and use it in GitHub Desktop.
Javascript Proxy Objects
This file contains 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 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); |
This file contains 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 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