Created
June 27, 2017 06:15
-
-
Save jonathanweiss/539333b5166e74f838c43a796aee9c17 to your computer and use it in GitHub Desktop.
Proxies can be quite useful
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 vCard = { | |
firstName: '', | |
lastName: '', | |
yearOfBirth: 0 | |
}; | |
// Simple logging: | |
const vCardLogged = new Proxy(vCard, { | |
set: (obj, prop, value) => { | |
console.log(`vCard got new value for key "${prop}": "${value}"`); | |
obj[prop] = value; | |
return true; | |
} | |
}); | |
// Proxies can be stacked: | |
const vCardValdidatedAndLogged = new Proxy(vCardLogged, { | |
set: (obj, prop, value) => { | |
// *Very* simple validations | |
if (prop === 'yearOfBirth') { | |
if (typeof value !== 'number' || value < 1900 || value > (new Date).getFullYear()) { | |
throw new Error(`Invalid value provided for "${props}": "${value}"`); | |
} | |
} else if (typeof value !== 'string') { | |
throw new Error(`That doesn't look like name: "${value}"`); | |
} | |
obj[prop] = value; | |
return true; | |
}, | |
// Calculated props | |
get: (obj, prop, value) => { | |
if (prop === 'age') { | |
return (new Date).getFullYear() - obj.yearOfBirth; | |
} | |
if (prop === 'fullname') { | |
return `${obj.firstName} ${obj.lastName}`; | |
} | |
return obj[prop]; | |
} | |
}); | |
const developer = Object.create(vCardValdidatedAndLogged, {}); | |
developer.firstName = 'Jonathan' | |
try { | |
developer.lastName = 42; | |
} catch (ex) { | |
console.error(ex); | |
} | |
developer.lastName = 'Weiss'; | |
developer.yearOfBirth = 1984; | |
console.log(`The developer "${developer.fullname}" is ${developer.age} years old.`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment