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:
class 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ę:
class 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:
let user = new User('john', 'smit');
Zapiszmy dane w naszym pozornym setterze:
user.full = 'eric jons';
Sprawdźmy, czy właściwości obiektu zmieniły się:
console.log(user.name); // 'eric'
console.log(user.surn); // 'jons'
console.log(user.full); // 'eric jons'