JavaScript Introducing ES2015 Classes Static Methods

Pedro Oliveira
Pedro Oliveira
1,272 Points

How can static methods be useful? Could you think on any scenario where it should be used?

I want to understand more about the nature of static methods. But I quite don't get why I would use them.

Is there any case scenario where it suits perfectly?

1 Answer

Greg Kaleka
Greg Kaleka
38,990 Points

Hi Pedro,

I'm not a JS developer, but static methods in JS are like class methods in other languages. They can definitely be useful in cases where it doesn't really make sense to create an instance of the class in question, or sometimes just for convenience (although you want to be careful of this - some consider it an anti-pattern).

The classic case for a static or class method is helper initialization methods. Let's say for example, that you have a class House, and your normal initialization method takes a parameter numFamilies, so that you can either create a normal single-family house, or a duplex, triplex or quadplex if numFamilies is 2, 3, or 4, respectively.

However, 90% of the time, you're just creating single-family home instances. So rather than always having to pass in 1, you create a helper initialization method that creates a single-family home (in some languages you could simply have 1 as a default value if it's not passed in, but bear with me).

This method would have to be a static method. You wouldn't create an instance of House and then call this helper method on the instance. That doesn't make sense. Houses don't make other houses. So you would call House.createSingleFamilyHome() and get your instance.

There are other examples, but I think this is the simplest one to understand. More broadly, it's what I said in the first paragraph. If it doesn't make sense to create an instance just to call the method, that's a use case for a static method.

Hope that helps!

Cheers :beers:

-Greg