Using Object.defineProperty to Add Getter and Setter in Javascript


Define getters and setters for an object property.

Source Code

let person = { firstName: 'John', lastName: 'Doe' };
Object.defineProperty(person, 'fullName', {
  get() {
    return `${this.firstName} ${this.lastName}`;
  },
  set(value) {
    [this.firstName, this.lastName] = value.split(' ');
  }
});
console.log(person.fullName);
person.fullName = 'Jane Doe';
console.log(person.firstName); // Jane
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments