Աքսեսորների սետտերները OOP-ում JavaScript-ում
Եկեք այժմ բացի գետտերից ստեղծենք նաև աքսեսորի սետտեր.
class User {
#name;
get name() {
return this.#name;
}
set name(name) {
this.#name = name;
}
}
Այժմ ավելացնենք ստուգում սետտերում.
class User {
#name;
set name(name) {
if (name.length > 0) {
this.#name = name;
} else {
throw new Error('name is incorrect');
}
}
get name() {
return this.#name;
}
}
Ստեղծենք դասի օբյեկտ.
let user = new User;
Գրենք տվյալներ մեր հատկության մեջ.
user.name = 'john';
Փորձենք գրել անվավեր տող և կստանանք սխալ.
user.name = '';
Իրականացրեք սետտերներ
Employee դասի հատկությունների համար.
Ավելացրեք ստուգումներ
Employee դասի աքսեսորների սետտերներում.