Javascript static methods
Created By: chatGPT
In JavaScript, static methods are functions that are defined on a class but are not called on instances of that class. Instead, they are called on the class itself. This is useful for utility functions that are relevant to the class but do not require access to instance properties.
class MathUtil {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
To call a static method, use the class name instead of an instance. Static methods can also be useful for encapsulating behavior that pertains to the class as a whole.
const sum = MathUtil.add(5, 10);
console.log(sum); // Output: 15
const product = MathUtil.multiply(4, 5);
console.log(product); // Output: 20
Static methods can also be private, starting in ES2022 with the syntax
#
. This allows better encapsulation in your classes, as private methods cannot be accessed outside of the class definition.class Example {
static #privateMethod() {
return 'This is a private method';
}
static publicMethod() {
return Example.#privateMethod();
}
}
You can access the private static method only through another static method within the same class. Here’s how you can call it:
console.log(Example.publicMethod()); // Output: 'This is a private method'
Static methods are also commonly used as factory methods. A factory method is generally used for creating instances of a class, allowing for more complex instance creation than the usual constructor.
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
static createAdult(name) {
return new User(name, 18);
}
}
Using the factory method, we can easily create an adult user instance without directly using the constructor.
const adultUser = User.createAdult('Alice');
console.log(adultUser); // Output: User { name: 'Alice', age: 18 }