پیشرفته
·
۹ دقیقه مطالعه
کلاسها و شیءگرایی
تعریف کلاس
class Account {
constructor(name) {
this.name = name;
this.xp = 0;
}
addXp(amount) {
this.xp += amount;
}
get level() {
return Math.floor(this.xp / 100) + 1;
}
}
ساخت نمونه
const acc = new Account("آرنا");
acc.addXp(250);
console.log(acc.level); // 3
constructorهنگامnewاجرا میشود.thisبه نمونهٔ ساختهشده اشاره دارد.getیک «خاصیت محاسبهشونده» میسازد (acc.levelبدون پرانتز).
وراثت
class Admin extends Account {
constructor(name) {
super(name); // سازندهٔ والد
this.isAdmin = true;
}
}
فیلد خصوصی
class Box {
#secret = 42; // # یعنی خصوصی
reveal() { return this.#secret; }
}
کلاسها در JS روی سیستم «prototype» ساخته شدهاند، اما این نحو مدرن، کار را ساده و خوانا کرده.