Normally, methods belong to instances: each cookie can do things. But sometimes a function is related to the class as a whole, rather than any one instance. For that, use static:
class Temperature {
static FREEZING = 0;
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return (this.celsius * 9) / 5 + 32;
}
static fromFahrenheit(f) {
return new Temperature(((f - 32) * 5) / 9);
}
isFreezing() {
return this.celsius <= Temperature.FREEZING;
}
}
const hot = new Temperature(35);
console.log(hot.fahrenheit);
const fromUS = Temperature.fromFahrenheit(212);
console.log(fromUS.celsius);
console.log(Temperature.FREEZING);
console.log(new Temperature(-3).isFreezing());
It prints
95 100 0 true
You call static methods and read static properties on the class itself (Temperature.fromFahrenheit), not on an instance. You've used static methods before without knowing it: Number.isNaN(), Array.from(), Object.keys() and Promise.all() are all static methods!