sajad torkamani
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' }

repl

Tagged: JavaScript

Leave a comment

Your email address will not be published. Required fields are marked *