Using the Object.defineProperty()
method, or manually writing getters and setters in your object?
Reasons one might be better than the other:
- Readability?
- Shorter code to type?
Object.defineProperty()
Example:
const person = {
firstName: 'Jimmy',
lastName: 'Smith'
};
Object.defineProperty(person, 'fullName', {
get: function() {
return firstName + ' ' + lastName;
},
set: function(name) {
let words = name.split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
});
console.log(person.fullName)
Manual Example:
const person = {
firstName: 'Jimmy',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName (name) {
let words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
}