Settery pozornych właściwości w OOP w JavaScript

Oprócz getterów pozornych właściwości można tworzyć również ich settery. W tym przypadku wewnątrz settera musimy pobrać dane, podzielić je i zapisać odpowiednie części w odpowiednie właściwości publiczne.

Spróbujmy. Zaimplementujmy setter pozornej właściwości full:

javascriptclass User {
  constructor(name, surn) {
    this.name = name;
    this.surn = surn;
  }
  
  get full() {
    return this.name + ' ' + this.surn;
  }
  
  set full(full) {
    let [name, surn] = full.split(' ');
    
    this.name = name;
    this.surn = surn;
  }
}

Uprośćmy destrukturyzację:

javascriptclass User {
  constructor(name, surn) {
    this.name = name;
    this.surn = surn;
  }
  
  get full() {
    return this.name + ' ' + this.surn;
  }
  
  set full(full) {
    [this.name, this.surn] = full.split(' ');
  }
}

Stwórzmy obiekt klasy:

javascriptlet user = new User('john', 'smit');

Zapiszmy dane w naszym pozornym setterze:

javascriptuser.full = 'eric jons';

Sprawdźmy, czy właściwości obiektu zmieniły się:

javascriptconsole.log(user.name); // 'eric'
console.log(user.surn); // 'jons'
console.log(user.full); // 'eric jons'