static
| Static fields | |
| Static factories | |
| Shared state | |
| this in static context |
Static fields
A static field belongs to the class itself, not to any object. Read it through the class name without calling new.
class App {
static version: string = "1.0";
}
console.log(App.version);
Static factories
A static method also runs without new. Factories use this to build objects with a clear name that explains the starting state.
class User {
constructor(public name: string) {}
static guest(): User {
return new User("Guest");
}
}
const guest = User.guest();
Shared state
All objects see the same static field. Counters and caches use this to share one value across every instance.
class Ticket {
static next: number = 1;
id: number;
constructor() {
this.id = Ticket.next;
Ticket.next = Ticket.next + 1;
}
}
this in static context
Inside a static method, this points to the class itself. Use it to read other static members so children inherit the same logic.
class Util {
static prefix: string = "app";
static label(name: string): string {
return this.prefix + ":" + name;
}
}
console.log(Util.label("start"));
Next: Getters and setters
Article author: Arthur Isaev