OOP (including classes) was recently added to JavaScript, and in my opinion, it's more like syntactic sugar that allows us to structure our data more easily, or perhaps just for the satisfaction of using the new
keyword. These OOP features were adapted from other languages, such as Java.
Static methods allow other pieces of your code to access variables and methods from a class without creating an instance of it (not using the new
keyword).
This is especially helpful when you want to retrieve data from a class without creating an instance or initializing the constructor.
Take, for example, a real world example of Web Components:
class WhyStatic {
/* other methods... */
static get observedAttributes() {
return ["name", "why", "test"];
}
}
This allows the custom elements function to access the observed attributes of an HTML element without creating an extra instance.
In other words, we can create non-instance specifc data for a class that gets accessed outside, and only outside, a class instance.
That's why we need static
in OOP.