जावास्क्रिप्ट में ओओपी में काल्पनिक गुणों के सेटर

काल्पनिक गुणों के गेटर के अलावा उनके सेटर भी बनाए जा सकते हैं। इस स्थिति में सेटर के अंदर हमें डेटा प्राप्त करना होगा, उसे विभाजित करना होगा और संबंधित भागों को उचित सार्वजनिक गुणों में लिखना होगा।

आइए कोशिश करते हैं। आइए काल्पनिक गुण 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'