JavaScript Reference ยท Classes and Modules
Static members in classes
Reference for JavaScript static class members: static methods, static fields, static initialization blocks, inheritance of statics and what this means inside them.
The static keyword puts a member on the class itself instead of on its instances. Static methods are the natural home for factories and utilities related to the class (Array.from(), Object.keys() and Promise.resolve() are all static). Static fields hold shared state such as counters or defaults. A static initialization block runs setup code once, when the class is defined.
class Id { static #next = 1; static create() { return new Id(Id.#next++); } constructor(value) { this.value = value; } }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
class Name { static method() {} static get accessor() {} static field = expression; static #privateField = expression; static #privateMethod() {} static { /* statements */ } }
thisinside a static member is the class the member was called on, which may be a subclass.- Static initialization blocks have their own scope for variables declared with
let,constandvar, can usethisfor the class, and can access private static members. A class may have several; they run in source order together with static field initializers. awaitandreturnare not allowed in a static block.
Usage notes
- Instances do not have statics.
new Name().staticMethodisundefined; callName.staticMethod(). Inside an instance method usethis.constructor.staticMethod()or the class name. - Subclasses inherit statics through the prototype chain of the constructors (
Object.getPrototypeOf(Circle) === Shape). Reading finds the parent's value; assigning toCircle.countcreates a separate property onCircle, as shown above, so a shared counter should be updated through the parent class name. - Static fields run once when the class is defined, not per instance.
- Static private members can only be reached through the class that declares them. Calling a static private method with
thisas a subclass throwsTypeError, so prefer the class name when using#x. - Reserved names. A static member cannot be called
prototype.static nameandstatic lengthare allowed but replace the built-in properties. - Not a namespace. For a bag of unrelated functions, an object or a module is simpler than a class of statics.
- Factories.
static from()orstatic create()can validate arguments before callingnew.
Browser support
Static methods work everywhere. Static fields and static blocks are newer; they work in all current browsers, but check a compatibility table for older targets.