Կեղծ հատկությունների սետտերներ OOP-ում JavaScript-ում

Կեղծ հատկությունների գետտերներից բացի կարելի է ստեղծել նաև դրանց սետտերները։ Այս դեպքում սետտերի ներսում մենք պետք է ստանանք տվյալները, բաժանենք դրանք և գրենք համապատասխան մասերը հարկավոր պուբլիկ հատկություններում։

Փորձենք։ Իրականացնենք 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;
  }
}

Պարզեցնենք դեստրուկտուրիզացիան.

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(' ');
  }
}

Ստեղծենք կլասի օբյեկտ.

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

Գրենք տվյալներ մեր կեղծ սետտերի մեջ.

javascriptuser.full = 'eric jons';

Ստուգենք, որ օբյեկտի հատկությունները փոխվել են.

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