Skip to content

Instantly share code, notes, and snippets.

@BolajiAyodeji
Last active March 3, 2019 18:45
Show Gist options
  • Save BolajiAyodeji/6869024a355df8ca12c4a8ac04abe47e to your computer and use it in GitHub Desktop.
Save BolajiAyodeji/6869024a355df8ca12c4a8ac04abe47e to your computer and use it in GitHub Desktop.
Getters and Setters with error handling
const person = {
firstName: 'Bolaji',
lastName: 'Ayodeji',
get fullName() {
return `${person.firstName} ${person.lastName}`
},
set fullName(value) {
if(typeof value !== 'string') {
throw new Error('Value is not a string');
}
const parts = value.split(' ');
if(parts.length !== 2) {
throw new Error('Enter a first and last name');
}
this.firstName = parts[0];
this.lastName = parts[1];
}
};
try {
person.fullName = '';
}
catch (e) {
alert(e);
}
console.log(person);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment