Skip to content

Instantly share code, notes, and snippets.

@JonAbrams
Created July 9, 2015 23:15
Show Gist options
  • Save JonAbrams/7edaa3545f8fd11a1919 to your computer and use it in GitHub Desktop.
Save JonAbrams/7edaa3545f8fd11a1919 to your computer and use it in GitHub Desktop.
How to add getter/setter methods to ES6 classes after the class is created
// Also works for normal methods
class User {
constructor (first, last) {
this.firstName = first;
this.lastName = last;
}
}
Object.defineProperty(User.prototype, 'name', {
get: function () {
return `${this.firstName} ${this.lastName}`
},
set: function (name) {
let split = name.split(' ');
this.firstName = split[0];
this.lastName = split[1];
}
});
let user = new User('jon', 'abrams');
console.log(user.name); // outputs "jon abrams"
user.name = "Jon Abrams";
console.log(user.name); // outputs "Jon Abrams"
@PaulAsaf2
Copy link

Thanks! It helped me resolve kata. Bad what I can not myself come to this solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment