A static method or variable is one that belongs to the class, not to instances of that class.
This means that static variables and methods are shared by all instances of the class.
Consequently, they cannot directly access instance properties, as they are not bound to any specific instance of the class.
Static Variables
In JavaScript, static variables are defined using the static keyword, which indicates that this property belongs to the class itself.
class Counter {
static counter = 0;
constructor() {
Counter.counter++;
}
static getCounter() {
return Counter.counter;
}
}
const c1 = new Counter();
const c2 = new Counter();
const c3 = new Counter();
console.log(Counter.getCounter()); // Shows 3
In this example:
Counter.counteris a static variable that increments each time a new instance of theCounterclass is created.Counter.getCounter()is a static method that allows access to the value of the static variablecounter, without needing to create an instance of the class.
Remember that static variables cannot be accessed through class instances. They are always accessed through the class itself.
Static Methods
Similarly, a static method is a method that belongs to the class rather than to an instance of the class. This means you can invoke the method directly on the class without needing to create an object.
Like variables, static methods are also defined using the static keyword.
class Mathematics {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
}
console.log(Mathematics.add(5, 3)); // Shows 8
console.log(Mathematics.subtract(5, 3)); // Shows 2
Here
- We have created a class called
Mathematicswith two static methods:addandsubtract. - Both methods can be invoked without creating an instance of the class.
