जावास्क्रिप्ट में ओओपी में काल्पनिक गुणों के सेटर
काल्पनिक गुणों के गेटर के अलावा उनके सेटर भी बनाए जा सकते हैं। इस स्थिति में सेटर के अंदर हमें डेटा प्राप्त करना होगा, उसे विभाजित करना होगा और संबंधित भागों को उचित सार्वजनिक गुणों में लिखना होगा।
आइए कोशिश करते हैं। आइए काल्पनिक गुण 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'