static Keyword
The static
keyword defines class-level fields and methods.
Static members belong to the class, not to its instances, and are accessed via the class name (or this
inside static methods).
Syntax
class C {
static x = 1; // static field
static method() { /* ... */ } // static method
static #p = 0; // private static field
static { // static initialization block
this.x += 1;
}
}
C.x; C.method();
Examples
// ১) বেসিক: স্থির কাউন্টার
শ্রেণী কাউন্টার {
স্থির গণনা = 0;
constructor() {
কাউন্টার.গণনা++;
}
স্থির রিসেট() {
কাউন্টার.গণনা = 0;
}
}
const a = নতুন কাউন্টার();
const b = নতুন কাউন্টার();
কনসোল.লগ(কাউন্টার.গণনা); // 2
কাউন্টার.রিসেট();
কনসোল.লগ(কাউন্টার.গণনা); // 0
// ২) ইনহেরিটেন্স: স্থির সদস্য সাবক্লাসেও পাওয়া যায়
শ্রেণী বেস {
স্থির কে = "Base";
স্থির বলো() { কনসোল.লগ("who:", এটি.কে); } // static e 'এটি' ক্লাসকে বোঝায়
}
শ্রেণী সাব প্রসারিত বেস {
স্থির কে = "Sub";
}
বেস.বলো(); // who: Base
সাব.বলো(); // who: Sub
// ৩) প্রাইভেট স্থির + static ব্লক
শ্রেণী কনফিগ {
স্থির #গোপন = "key";
স্থির মান = 0;
স্থির { // ক্লাস লোডের সময় একবারই চলে
এটি.মান = এটি.#গোপন.length;
}
স্থির নাও() { ফেরত এটি.#গোপন; }
}
কনসোল.লগ(কনফিগ.মান); // 3
কনসোল.লগ(কনফিগ.নাও()); // "key"
// ৪) ইনস্ট্যান্সে নেই
const x = নতুন কনফিগ();
কনসোল.লগ(x.মান); // undefined
// x.নাও(); // TypeError: function নয়
Notes
- Static members are accessed via the class, not via instances.
- Inside a static method,
this
refers to the constructor (class), so statics naturally work with inheritance (Sub.say()
usesSub
asthis
). - Private static fields/methods (
static #x
) are scoped to the declaring class and not inherited. - Static initialization blocks run once when the class is evaluated; useful for complex setup that needs access to private statics.
- Prefer static factory methods (
from(...)
,of(...)
) for alternative construction paths. - Keep one language style (English/Bangla/Banglish) per file.