In JavaScript, static methods belong to the class itself rather than to instances of the class. These methods are called on the class directly and do not require an instance to be invoked. Static methods are useful for utility functions or operations that don't depend on instance-specific data.
• Declaration: Use the static keyword to declare a static method.
• Naming: Static methods can have any name.
• Multiple Static Methods: A class can contain multiple static methods.
• Overriding: If more than one static method with the same name is declared, the last one will override the previous ones.
• Utility Functions: Static methods are often used for utility functions that operate on data or perform tasks that don't depend on instance state.
• Utility Functions: You can call static methods directly on the class. They cannot be called using this within instance methods but can be called using the class name.
class ClassName {
static methodName() {
// Method definition
}
}
<script>
class MathUtils {
static add(a, b) {
return a + b;
}
}
document.write(MathUtils.add(5, 3)); // Output: 8
</script>
In this example, the add method is static, so it is called directly on the MathUtils class.
<script>
class User {
constructor(name) {
this.name = name;
}
static greet() {
document.write('Hello!');
}
displayGreeting() {
// Calling static method from instance method
User.greet();
}
}
const user = new User('Alice');
user.displayGreeting(); // Output: Hello!
</script>
In this example, the greet method is static and is called from the displayGreeting instance method using the class name User.
<script>
class Calculator {
static multiply(x, y) {
return x * y;
}
static square(x) {
// Calling another static method
return this.multiply(x, x);
}
}
document.write(Calculator.square(4)); // Output: 16
</script>
Here, the square method is a static method that calls another static method multiply within the same class.
• Static Methods: These methods are associated with the class itself and not with instances.
• Direct Access: They are accessed directly using the class name and not via instances.
• No this for Static Methods: this cannot be used to call static methods within instance methods. Instead, call static methods using the class name or as a property of the constructor.