0
votes

Hi at this code example i can't fully understand when the setter fullname method gets called from the constructor why the constructor does not create also a property "fullname" but it just invokes the setter and moves to the next line.

Can someone explain to me what happens in detail it will be much appreciated.

class Person {
  constructor(fullname, birthYear) {
    this.fullname = fullname;
    this.birthYear = birthYear;
  }          
  set fullname(name) {
    if (name.includes(' ')) this._fullname = name;
    else alert(`${name} is not a full name`);
  }
 
  get fullname() {
    return this._fullname;
  }
}
 
const personObj = new Person('FirstName Lastname', 1999);
console.log(personObj);
2

2 Answers

0
votes

By the time the constructor gets called, this has already been created, with Person as it's prototype. Because of the prototype, this.fullname is a pair of setter and getter functions. If you attempt to assign to it, the standard behavior for setters and getters occurs, and the setter will be called. The behavior doesn't get modified due to being inside a constructor function.

0
votes

The constructor does not create a new property named fullname since that property already exists, defined by the getter and setter. However it is not a data property but an accessor property, so it holds no value of it's own.