Search code examples
javascriptclassconstructorgetter-setter

What exacly happens when a class constructor calls a setter


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);

Solution

  • The new keyword creates an object with the prototype of Person, then calls the constructor. So by the time the constructor is called, it already has that object, and that object has a pair of setters and getters for this.fullname. If you attempt to assign to this.fullname, 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.