ref – https://stackoverflow.com/questions/45594196/difference-between-static-function-declaration-and-the-normal-function-declarati
That’s the very definition of a static function that you don’t have to instantiate the class to call it. That’s not something JS specific.
A static method is callable from the class itself
A non-static method is callable from an instance of the class, so you basically have to create an object before being able to access that method.
1 2 3 4 5 6 7 8 9 10 11 |
class Foo{ ... static fn() {...} } than class Foo { ... } Foo.fn = function(){...}; |
Although in the end, both is just little more than:
1 2 3 |
function Foo(){...} Foo.fn = function(){}; // + Foo.prototype stuff |
es6 classes just make it look nicer. Syntactical sugar.
For example, for a addNumbers(var a, var b) which does return a+b, is it really necessary to waste memory instantiating an object of the class just to add those 2 numbers? No, you just need the result and that’s the whole point of having static.
Using the first style allows you to group methods in a particular class (think of something like namespaces). Maybe you can define classes like Math and String, which both have the add method but implemented in a different way. Calling add() by itself would be confusing, but Math.add() and String.add() are not.