Hint
static members belong to the class itself, not instances; class fields vs constructor assignments have subtle initialization order differences
Static members belong to the class itself, not to any instance. Accessed via the class name.
class Counter {
static count = 0; // shared across all instances
id: number;
constructor() {
Counter.count++; // increment class-level counter
this.id = Counter.count;
}
static reset() {
Counter.count = 0;
}
static getInstance() {
return new Counter();
}
}
const a = new Counter(); // Counter.count = 1
const b = new Counter(); // Counter.count = 2
console.log(Counter.count); // 2
Counter.reset();
console.log(Counter.count); // 0
Class fields vs constructor assignment:
class Example {
// Class field — initialized BEFORE constructor body
x = 10;
y = this.x * 2; // ✅ x is already 10
// Method defined as field — each instance gets its own copy
handleClick = () => {
console.log(this.x); // 'this' is always correct — no binding needed
};
constructor() {
// Class fields are set BEFORE this runs
console.log(this.x); // 10
}
}
// vs prototype method — shared across all instances
class ExampleProto {
handleClick() {
// 'this' depends on how it's called — may need .bind()
console.log(this);
}
}
handleClick = () => {}) solve the React event handler binding issue — no need for .bind(this) in the constructor. The trade-off is each instance gets its own function copy rather than sharing a prototype method.