JavaScript: static classes

How to create a static class in JavaScript?

Fabio Costa
Aug 6, 2020

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.

A static class can be used as a convenient container for methods that just operate on input parameters and do not have to get or set any internal instance fields.

How to prevent a class from being instantiated? Create a constructor function and throw an error:

class StaticClass {  constructor() {
if (this instanceof StaticClass) {
throw Error('A static class cannot be instantiated.');
}
}
static method() {}}

.

Source: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members

--

--

No responses yet