class Keyword
Use class
to define blueprints for objects.
Classes can have a constructor, methods, fields (including private #fields
), getters/setters, static members, and support inheritance via extends
and super
.
Syntax
class Account {
#balance = 0; // private field
currency = "BDT"; // public field
constructor(owner, opening = 0) {
this.owner = owner; // instance property
this.deposit(opening); // call method
}
deposit(amount) { // instance method
this.#balance += amount;
}
get balance() { // getter
return this.#balance;
}
set balance(v) { // setter (validate)
if (v < 0) throw new Error("negative");
this.#balance = v;
}
static bank = "BNL Bank"; // static field
static from(user) { // static factory
return new Account(user, 0);
}
}
class Savings extends Account { // inheritance
constructor(owner, opening, rate = 0.05) {
super(owner, opening); // call parent constructor
this.rate = rate;
}
accrue() {
this.#balance = this.balance * (1 + this.rate); // via getter or internal logic
}
}
Examples
const a = নতুন হিসাব("Mamun", 1000);
a.জমা(500);
দেখাও("ব্যালেন্স:", a.ব্যালেন্স); // getter
const b = সঞ্চয়.থেকে?; // উদাহরণস্বরূপ আলাদা কন্সট্রাকশন
const c = হিসাব.from("Rafi"); // স্থির ফ্যাক্টরি
কনসোল.লগ(হিসাব.ব্যাংক); // স্থির ফিল্ড
Notes
- Fields declared directly inside the class body are set up per‑instance at construction;
static
fields belong to the class constructor. - Call
super(...)
in a subclass constructor before accessingthis
. - Private fields
#name
are truly private (not accessible viathis["#name"]
). Names are lexical, not dynamic. - Methods are on the prototype; arrow functions as fields create a new function per instance (useful for
this
binding, but increases memory). - Keep language style consistent per file; in Bangla/Banglish, aliases are:
শ্রেণী
/shreni
,প্রসারিত
/prosarito
,অভিভাবক
/obhibhabok
,স্থির
/sthir
,নতুন
/notun
.