Web Analytics

Static Members

Beginner~15 min

Static members belong to the class itself, not instances. They're perfect for utility functions and shared data.

Static Properties and Methods

Output
Click Run to execute your code
Static vs Instance:
  • Static: Accessed via class name (e.g., Math.PI)
  • Instance: Accessed via object (e.g., user.name)
  • Static members are shared across all instances
  • Cannot access instance members from static methods

When to Use Static

  • Utility functions: Math operations, formatters
  • Constants: Shared configuration values
  • Factory methods: Alternative constructors
  • Counters: Track total instances

Common Mistakes

1. Accessing Instance Members from Static

class User {
    userName: string = "Alice";
    
    static greet() {
        console.log(this.userName);  // ✗ Error!
    }
}

// ✓ Static can only access static
class User {
    static defaultName = "Guest";
    
    static greet() {
        console.log(this.defaultName);  // ✓ OK
    }
}

2. Using 'this' Instead of Class Name

class Counter {
    static count = 0;
    
    increment() {
        this.count++;  // ✗ Wrong - 'this' is instance
    }
}

// ✓ Use class name
class Counter {
    static count = 0;
    
    increment() {
        Counter.count++;  // ✓ Correct
    }
}
Best Practice: Use static for utility functions that don't need instance data. Examples: Math.max(), Array.isArray()

Summary

  • Static members belong to the class, not instances
  • Access via class name: ClassName.member
  • Perfect for utilities, constants, factories
  • Cannot access instance members from static

What's Next?

Congratulations! Module 3 complete. Next: Advanced Types!