Which is "better" to use for creating getters and setters?

Using the Object.defineProperty() method, or manually writing getters and setters in your object?

Reasons one might be better than the other:

  1. Readability?
  2. 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] || '';
    }
}

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.