Class Static in JavaScript
?? Static Methods and Properties in JavaScript Classes
What are Static Members?
Static methods/properties belong to the class itself, not to instances (objects created from the class).
You call them directly on the class, not on an object.
Useful for utility functions or constants related to the class.
Syntax
class MyClass { static staticMethod() { console.log("This is a static method."); } static staticProperty = "Static property value"; instanceMethod() { console.log("This is an instance method."); }}// Calling static methodMyClass.staticMethod(); // Output: This is a static method.// Accessing static propertyconsole.log(MyClass.staticProperty); // Output: Static property value// Trying to call static method on instance (will fail)const obj = new MyClass();obj.staticMethod(); // Error: obj.staticMethod is not a functionExample: Static vs Instance
class Circle { constructor(radius) { this.radius = radius; } // Instance method area() { return Math.PI * this.radius ** 2; } // Static method static description() { return "Circles are round shapes."; }}const c = new Circle(5);console.log(c.area()); // Output: 78.53981633974483console.log(Circle.description()); // Output: Circles are round shapes.Use Cases for Static Methods
Utility/helper functions related to the class but not tied to an instance
Factory methods to create instances
Constants related to the class
Static Properties Support
Supported in modern JavaScript (ES2022+)
For older environments, static properties can be assigned outside the class:
class Example {}Example.staticValue = 123;console.log(Example.staticValue); // 123Would you like examples of static factory methods, or using static properties for constants?