JavaScript getters and setters: example usage
26 June 2022 (Updated 26 June 2022)
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Object.defineProperty(Person.prototype, 'fullName', {
get: function() {
return `${this.firstName} ${this.lastName}`
},
set: function(newValue) {
const [firstName, lastName] = newValue.split(' ')
if (!firstName || !lastName) {
return
}
this.firstName = firstName
this.lastName = lastName
}
})
const person = new Person('John', 'Doe')
console.log({
firstName: person.firstName,
lastName: person.lastName,
fullName: person.fullName
})
person.fullName = 'Alice Smith'
console.log({
firstName: person.firstName,
lastName: person.lastName,
fullName: person.fullName
})
Output:
{ firstName: 'John', lastName: 'Doe', fullName: 'John Doe' }
{ firstName: 'Alice', lastName: 'Smith', fullName: 'Alice Smith' }
Tagged:
JavaScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment