Static Fields and Methods
A class can have static fields and methods.
class MathUtilities {
static PI = 3.14;
static max(...args) {
let max = Number.MIN_SAFE_INTEGER;
args.forEach((arg) => (max = max < arg ? arg : max));
return max;
}
}
console.log(MathUtilities.PI); // 3.14
console.log(MathUtilities.max(3, 0, 5)); // 5
Just like in Java/C++, static fields and methods in JavaScript are class members, not instance members. So you access or invoke them using the class name, not the instantiated object.
Note that in JavaScript a class is technically a function. Since a function is technically an object, a class is also an object. You can add value or function properties to it outside of the class definition. Those additions are static members.
class Person {
constructor(name) {
this.name = name;
}
}
Person.genus = "homosapien";
const person = new Person("Ali");
console.log(person); // {"name":"Ali"}
console.log(Person.genus); // homosapien
My advice is to avoid adding properties the way genus was added to the Person class. Instead, define it as a static field inside the class declaration. More generally, a field or a utility function that applies to all instances of a class but does not work with instance data should be a static member.