Կեղծ հատկությունների սետտերներ OOP-ում JavaScript-ում
Կեղծ հատկությունների գետտերներից բացի կարելի է ստեղծել նաև դրանց սետտերները։ Այս դեպքում սետտերի ներսում մենք պետք է ստանանք տվյալները, բաժանենք դրանք և գրենք համապատասխան մասերը հարկավոր պուբլիկ հատկություններում։
Փորձենք։ Իրականացնենք
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;
}
}
Պարզեցնենք դեստրուկտուրիզացիան.
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(' ');
}
}
Ստեղծենք կլասի օբյեկտ.
let user = new User('john', 'smit');
Գրենք տվյալներ մեր կեղծ սետտերի մեջ.
user.full = 'eric jons';
Ստուգենք, որ օբյեկտի հատկությունները փոխվել են.
console.log(user.name); // 'eric'
console.log(user.surn); // 'jons'
console.log(user.full); // 'eric jons'