The other day I started a new project at my job. I was setting up the repo and adding all of our usual linters to hold ourselves to a consistent standard. Once I had eslint set up with the latest versions, something popped up that I hadn’t had to think about in a while: static methods.
We had a javascript class with a mix of intense methods and some that yes technically should be considered static methods.
As a refresher (from MDN Web docs):
Static methods aren’t called on instances of the class. Instead, they’re called on the class itself. These are often utility functions, such as functions to create or clone objects.
So what does this mean? Static methods hold logic that do not interact with an instance of the class (ie. this
)
For example:
class Person {
constructor (name) {
this.name = name;
}
static sayHello (name) {
alert(`Hello ${name}!`);
}
}
sayHello
is a static method because it does not involve an instance of Person (it does not call this
). We can call sayHello
by doing something like:
Person.sayHello(‘Denzel’)
Now, if we want to add another method to our Person class, that calls sayHello
, we could need to call it as a property of the constructor. Static methods are not directly accessible using the this
keyword from non-static methods.
class Person {
constructor(name) {
this.name = name;
}
interact() {
this.constructor.sayHello(this.name);
}
static sayHello(name) {
alert(`Hello ${name}!`);
}
}
You can however call a static method from inside another static method using this
as this
represents the class itself, not the instance.
class Person {
static interact(name) {
this.sayHello(name);
}
static sayHello(name) {
alert(`Hello ${name}!`);
}
}
Person.interact(‘Denzel Washington’);
I hope that clarifies static methods! I was blinding following the linter rules and neglected to realize how static methods truly work. For more information, check out this
reference