Class Static is a concept in object-oriented programming that allows developers to create methods and properties that belong to a class rather than an instance of that class. In other words, static members are shared across all instances of a class and can be accessed without creating an object of that class.
Static members are defined using the static keyword in the class definition. They can be accessed using the class name followed by the member name, without the need to create an instance of the class. This makes static members useful for creating utility functions or constants that are used throughout an application.
Here is an example of a class with a static method:
class MathUtils {
static add(a, b) {
return a + b;
}
}
console.log(MathUtils.add(2, 3)); // Output: 5
In this example, the MathUtils class has a static method called add that takes two arguments and returns their sum. The add method can be called using the class name without the need to create an instance of the MathUtils class.
Static members can also be used to create constants that are used throughout an application. Here is an example:
class Constants {
static PI = 3.14159;
}
console.log(Constants.PI); // Output: 3.14159
In this example, the Constants class has a static property called PI that is set to the value of pi. The PI property can be accessed using the class name without the need to create an instance of the Constants class.
Static members can also be used to create utility functions that are used throughout an application. Here is an example:
class StringUtils {
static reverse(str) {
return str.split('').reverse().join('');
}
}
console.log(StringUtils.reverse('hello')); // Output: 'olleh'
In this example, the StringUtils class has a static method called reverse that takes a string argument and returns the reversed string. The reverse method can be called using the class name without the need to create an instance of the StringUtils class.
Static members can also be used to create factory methods that are used to create instances of a class. Here is an example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
static create(name, age) {
return new Person(name, age);
}
}
const john = Person.create('John', 30);
console.log(john.name); // Output: 'John'
console.log(john.age); // Output: 30
In this example, the Person class has a static method called create that takes two arguments and returns a new instance of the Person class. The create method can be called using the class name without the need to create an instance of the Person class.
Static members are a powerful feature of object-oriented programming that can be used to create utility functions, constants, factory methods, and more. By using static members, developers can create more efficient and maintainable code that is easier to read and understand.