JavaScript Class Static

Static methods in JavaScript classes are defined using the static keyword. These methods belong to the class itself, not to instances of the class, and are often used for utility functions or constants.

Key Topics

Defining Static Methods

Static methods are declared using the static keyword and can be called directly on the class without creating an instance.

class MathUtils {
    static add(a, b) {
        return a + b;
    }
}
console.log(MathUtils.add(5, 3));

Output

> 8

Explanation: The add method is defined as static, allowing it to be called directly on the MathUtils class without instantiating an object.

Accessing Static Methods

Static methods are accessed directly on the class and cannot be called on class instances.

class Utils {
    static greet() {
        return "Hello from static method!";
    }
}
console.log(Utils.greet());

Output

> Hello from static method!

Explanation: The static method greet is accessed directly on the Utils class, as it does not belong to any instance.

Common Use Cases

Static methods are often used for utility functions, constants, or factory methods that operate independently of class instances.

class Config {
    static appName = "MyApp";
    static getVersion() {
        return "1.0.0";
    }
}
console.log(Config.appName);
console.log(Config.getVersion());

Output

> MyApp

> 1.0.0

Explanation: The static property appName and static method getVersion are accessed directly on the Config class for application-wide configuration.

JavaScript Usage in DOM

Below is a complete DOM example using a static method to perform utility calculations and display the result dynamically.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Class Static in DOM</title>
</head>
<body>
    <button onclick="calculateSum()">Calculate Sum</button>
    <p id="output"></p>

    <script>
        class Calculator {
            static add(a, b) {
                return a + b;
            }
        }
        function calculateSum() {
            const result = Calculator.add(10, 15);
            document.getElementById("output").textContent = `Sum: ${result}`;
        }
    </script>
</body>
</html>

Key Takeaways

  • Static Methods: Belong to the class itself, not its instances.
  • Direct Access: Access static methods directly using the class name.
  • Utility Functions: Use static methods for reusable, instance-independent logic.
  • DOM Integration: Leverage static methods to perform utility tasks dynamically in web applications.