Accessing Static Members
What you'll learn: How to correctly access static properties and methods from different contexts: outside the class, inside instance methods, and from other static members.
The Core Idea
Static members belong to the class itself, not to instances. This means you access them differently depending on where you're calling from:
- Outside the class: Use the class name as a namespace
- Inside instance methods: Still use the class name (not
this) - Inside static methods: Use the class name, or sometimes
this(which refers to the constructor)
Think of static members like a notice board in a school building. The board belongs to the school itself, not to any individual student. Whether you're a student (instance), a teacher (another instance), or someone walking by (external code), you always look at "SchoolName.noticeBoard" — you never say "myStudentID.noticeBoard."
Accessing from Outside the Class
Use the class name directly, like a namespace:
class Counter {
static count = 0;
static increment(): void {
Counter.count++;
}
}
// Access from outside
console.log(Counter.count); // 0
Counter.increment();
console.log(Counter.count); // 1
Accessing from Instance Methods
Instance methods must also use the class name to access static members:
class Logger {
static appName = "MyApp";
logMessage(message: string): void {
// Use class name, NOT this
console.log(`[${Logger.appName}] ${message}`);
}
}
const logger = new Logger();
logger.logMessage("Hello"); // [MyApp] Hello
You cannot write this.appName inside logMessage — this refers to the instance, which doesn't have appName.
Accessing from Static Methods
Inside static methods, you can use either the class name or this (which refers to the constructor function):
class Config {
static version = "1.0";
static getInfo(): string {
// Both work:
return `Version: ${Config.version}`;
// OR: return `Version: ${this.version}`;
}
}
Using the class name is generally clearer and more explicit.
Key Takeaway: Always access static members through the class name (like ClassName.member), whether you're outside the class or inside an instance method. This makes it clear you're accessing class-level data, not instance-level data.