Search code examples
javascriptjavascript-objectses6-class

When exactly setter function is ES6 class is called, when we use the same name for the name of the setter as the name of the property?


Since yesterday I am wondering when exactly the setter method for fullName is being called by JS behind the scenes?

I was trying to figure it out on my own, but i could not. I know, that it happens, when we write this.fullName = fullName but how? this.fullName is undefined before 3rd line, so when we set it, fullName, before calling "this.fullName" is equal to the argument, that we pass in.

After the instruction this.fullName = fullName this.fullName is equal to the passed argument, and fullName is still this argument passed to a constructor.. So when and how this setter is called? How does JS know, that it should call the setter, and not just simply assign argument to a variable?

class PersonCL {

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

}

Solution

  • When you define a getter and/or setter of a class property, this is implemented as a property descriptor in the class prototype. The property is defined something like this:

    Object.defineProperty(PersonCL.prototype, 'fullName', {
        set: function(name) {
            if (name.includes(' ')) this._fullName = name;
            else alert(`${name} is not a full name!`);
        },
        get: function() {
            return this._fullName;
        }  
    });
    

    This is done when the class definition is executed. When a class instance is created, it inherits from the prototype, so the descriptor is inherited. The set function is called when the constructor assigns to this.fullName.

    See the MDN documentation of Object.defineProperty()