In JavaScript classes, it’s possible to create static fields or 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/methods in JavaScript are class members, not instance members. Therefore, you should access or invoke them using the class name, not the instantiated object.
Please 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 outside of the class definition. These additions are considered 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 within the class declaration. In a broader context, fields and utility functions that are applicable to all instances of a class, but do not operate on instance data, are ideal candidates for static methods.