Created
July 9, 2015 23:15
-
-
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
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
// 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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! It helped me resolve kata. Bad what I can not myself come to this solution.