Static Methods

Posted by Nolan Hughes on November 19th, 2018

I wanted to talk about static methods in JavaScript today. At their core, static methods are just functions that are assigned to the class. Static methods in JavaScript are similar to class methods in Ruby. It’s important to note that they can’t be called on instances of a class.

Let’s look at an example.

class User { static staticMethod() { alert(this === User); } }
User.staticMethod(); // true

The above example demonstrates calling the method on a class, User, and what it returns. In general, static methods are used to implement functions that belong to the class, but not to any particular instance of it.

Note: The rule for this inside of a static method is that the value of this is the class constructor as shown above.

To really drive it home, the below example demonstrates sorting instances of a class with a static method.

class Dog { constructor(name, age) { this.name = name; this.age = age; }
static compare(dogA, dogB) { return dogA.age - dogB.age; } }
// usage let dogs = [ new Dog("Fido", 10), new Dog("Rover", 5), new Dog("Cinder", 13) ];
dogs.sort(Dog.compare);
alert( dogs[0].name ); // Rover

Here we have Dog.compare encapsulating the dog instances so as to compare them. It doesn't act on the dogs themselves but on the class of Dog.