Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialPedro Oliveira
1,272 PointsHow 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
39,021 PointsHi 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
-Greg