Static Methods
By default, the properties and methods you write inside a class belong to the instances (the specific objects created using the new keyword).
However, sometimes you need functionality that belongs to the class itself as an overarching concept, rather than to an individual instance. This is where static members come in.
Using Static Members
A static method or property is bound directly to the class definition. Instances of the class cannot access static members.
class User {
// A static property tracking state across ALL instances
static numUsers = 0;
constructor(name, age) {
this.name = name;
this.age = age;
// Increment the static counter
User.numUsers++;
}
// A static method
static getNumUsers() {
return User.numUsers;
}
}
const lane = new User("Lane", 30);
const allan = new User("Allan", 30);
// Accessing the static method on the Class itself
console.log(User.getNumUsers()); // Output: 2
// Attempting to access it on an instance throws an error
console.log(lane.getNumUsers());
// TypeError: lane.getNumUsers is not a function
When to Use Static Methods
Static methods are typically used to create utility or helper functions that are related to the class conceptually, but don’t require any instance-specific data (they don’t need access to this.name, etc.). For example, Math.round() or Date.now() are static methods built into JavaScript!