A static "method" is just a regular function that is attached to a class. This is useful when it belongs to that class semantically, and in extreme cases necessary in an inheritance hierarchy. The class name provides a visual namespace for accessing the function, e.g. Map.from does something different than Set.from.
However, you would only ever do that when you already have an existing class. You would never create an empty class only to put a static method inside it. In such a case, a simple object literal with a regular object method suffices:
const MyObject = {
myFunction() {
console.log('foo');
},
};
MyObject.myFunction();
Answer from Bergi on Stack Overflowoop - Why would you build a static function in Javascript when you can build a regular function? - Stack Overflow
What are your thoughts on Static Methods?
Static method in class is recognised as a function, but when called it returns undefined
Concretely, what is the purpose of static method in es6 ?
Videos
A static "method" is just a regular function that is attached to a class. This is useful when it belongs to that class semantically, and in extreme cases necessary in an inheritance hierarchy. The class name provides a visual namespace for accessing the function, e.g. Map.from does something different than Set.from.
However, you would only ever do that when you already have an existing class. You would never create an empty class only to put a static method inside it. In such a case, a simple object literal with a regular object method suffices:
const MyObject = {
myFunction() {
console.log('foo');
},
};
MyObject.myFunction();
Mostly for namespacing. Imagine you need 10 functions of related feature. Instead of taking up 10 names from global scope, using static methods you use just one global name, being the class name.
Remember that apps often end up being complex, using 3rd party libraries. Name clashes is a real problem when complexity comes to play.
Does this apply to JavaScript?
Static methods usually indicate a method that doesn't know where it belongs. It is sitting out there trying to belong to the class it is on, but it doesn't really belong, because it doesn't use the internal state of the class. When we look at our classes from the Single Responsibility Principle (SRP) viewpoint, a static method is usually a violation because it tends to have a responsibility that is not the same of the class it is attached on.