Static Members
In this page:
Static Properties
A static property is shared by the class itself and is accessed using the class name rather than an instance, so you do not need to create an object just to read or update it.
Example: Static Properties
class Counter {
static count: number = 0;
}
Counter.count++;
console.log(Counter.count);
Static Methods
Static methods are called using the class name and are useful when an operation does not depend on any particular instance's data, such as a helper that creates or validates objects of that class.
Example: Static Methods
class MathUtils {
static square(n: number): number {
return n * n;
}
}
console.log(MathUtils.square(5));
Static and Instance Members
Instance members belong to individual objects, while static members belong to the class as a whole, so changing a static property affects every reference to it across the whole program at once.
Example: Static and Instance Members
class Counter {
static total: number = 0;
constructor() {
Counter.total++;
}
}
new Counter();
new Counter();
console.log(Counter.total);
Static Members and this
Static methods operate in the context of the class rather than any single instance, so they cannot use this to refer to instance properties — there simply isn't an instance to refer to inside a static method.
Example: Static Members and this
class Config {
static appName: string = "MyApp";
static getName(): string {
return Config.appName; // uses class name, not "this"
}
}
console.log(Config.getName());
Common Uses of Static Members
Static members are commonly used for constants, counters, factory methods, and utility functions that logically belong with a class but don't need per-object state to do their job.
Example: Common Uses of Static Members
class IdGenerator {
private static nextId: number = 1;
static generate(): number {
return IdGenerator.nextId++;
}
}
console.log(IdGenerator.generate(), IdGenerator.generate());
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: