โ What Are Static Methods and Properties?
- Static methods and properties belong to the class itself, not to instances of the class.
- You call static methods directly on the class, not on objects created from it.
- Useful for utility functions, constants, or helper methods related to the class but not tied to any specific object.
๐ Basic Syntax for Static Methods
jsCopyEditclass MathHelper {
static square(x) {
return x * x;
}
}
console.log(MathHelper.square(5)); // 25
const mh = new MathHelper();
// mh.square(5); // โ Error: square is not a function on instances
static
keyword defines the static method.- Trying to call the method on an instance causes an error.
๐ Static Properties (ES2022+)
You can also define static properties directly in the class:
jsCopyEditclass Circle {
static pi = 3.14159;
constructor(radius) {
this.radius = radius;
}
area() {
return Circle.pi * this.radius ** 2;
}
}
console.log(Circle.pi); // 3.14159
const c = new Circle(5);
console.log(c.area()); // 78.53975
๐ Use Cases for Static Members
- Constants: Like
Math.PI
or configuration values. - Utility functions: Helper methods related to the class but donโt require instance data.
- Factory methods: Create instances with preset options.
Example of a factory static method:
jsCopyEditclass User {
constructor(name, role) {
this.name = name;
this.role = role;
}
static guestUser() {
return new User("Guest", "guest");
}
}
const guest = User.guestUser();
console.log(guest.name); // Guest
๐ Accessing Static Members from Instance Methods
Inside instance methods, to access static members, use the class name:
jsCopyEditclass Counter {
static count = 0;
constructor() {
Counter.count++;
}
getCount() {
return Counter.count;
}
}
const a = new Counter();
const b = new Counter();
console.log(a.getCount()); // 2
console.log(Counter.count); // 2
Summary Table
Feature | Usage | Called On |
---|---|---|
Static Method | static methodName() {} | Class itself |
Static Property | static propName = value; | Class itself |
Instance Method | methodName() {} | Instances |
Access Static in Instance | Use ClassName.staticMember | From instance methods |
Practice Challenge
- Create a class
Temperature
with a static methodcelsiusToFahrenheit(c)
converting Celsius to Fahrenheit. - Add a static property
freezingPoint
set to 0. - Use these static members without creating an instance.