HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Class Static

Static class methods are defined on the class itself. You cannot call a static method on an object instance, only on the class template. This makes them perfect for utility functions that don't depend on specific object data.


The static Keyword

Use the static keyword to define a static method:

class Car {
  constructor(name) {
    this.name = name;
  }
  static hello() {
    return "Hello!!";
  }
}

let myCar = new Car("Ford");

Calling Static Methods

Static methods be called on the Class, not on the instance:

// Correct:
console.log(Car.hello());

// Incorrect: This will throw an error
// console.log(myCar.hello()); 

Why use Static Methods?

  • Utility Functions: Methods that perform a general task (like formatting a date or comparing two objects) that don't need access to instance data ( this.name, etc.).
  • Namespace Organization: Groups related constants or helper logic under a categorical class name.
  • Global Access: Allows logic to be accessed globally via the class name without needing to spawn a new object new Class().

Example: Object Comparison

class User {
  constructor(name) {
    this.name = name;
  }
  static compare(user1, user2) {
    return user1.name === user2.name;
  }
}

let u1 = new User("Mim");
let u2 = new User("Mim");

User.compare(u1, u2); // returns true
Tip: If you need to access a static method inside another method of the same class, you can't use this. You must use the class name: ClassName.staticMethod().

Key Points to Remember

  • Static methods belong to the class, not to the instances (objects)
  • They are declared using the static keyword
  • You call them using the Class Name
  • They are ideal for Logic and Utilities that don't require object state
  • They prevent memory waste by avoiding the duplication of methods across all instances
  • Static properties are also supported (to store shared data/constants)