I don't really catch what is the purpose of putting a static method into a class and then calling it with this class instead of just creating a function with the same code.
class test {
static sum(a,b){
return (a+b)
}
}
sum = (a,b) => a+b
console.log(sum(10,5)) //15
console.log(test.sum(10,5)) //15
What is the difference? And why do people use static classes?
There's indeed no real technical difference between a standalone function and a static method on a class. You should not unnecessarily wrap your functions in a class, if there's no difference.
However, it can be advantageous for comprehensibility. For example, the builtin Date
class has a few static methods, like Date.now
. This clearly makes sense to have on the Date
class, since it's very Date
related. If it wasn't a static method on Date
, it'd be a global function, which would need to be named something useful and which shouldn't clash with other global names. Just naming it now
would probably take up a valuable global name and lead to confusion or clashes. Compare:
let foo = now();
let bar = Date.now();
Date.now
is much clearer here and also doesn't take up another global name.
Now (pun intended), ES6 modules somewhat solve this problem, as it gives you another tool to group related functionality: modules. With modules, you can simply export a standalone function and a separate class from your module, and the caller can use it as they please:
import { now, Date } from 'hypothetical-date';
let foo = now();
let bar = new Date;
// or
import hdate from 'hypothetical-date';
let foo = hdate.now();
let bar = new hdate.Date;