liveBook · Manning

Static field

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A property defined on a class or constructor itself rather than on instances created from it.

If every object created from a class needs the same setting, put it on the class itself. A static field belongs to the class object (the constructor), not to instances or the prototype. In class syntax, write it with the `static` keyword. section 27.6

class DataStore {
  static domain = 'https://example.com';       1
  static url(path) {                           2
    return `${this.domain}${path}`
  }
  constructor(resource) {
    this.url = DataStore.url(resource);        3
  }
}

const userStore = new DataStore('/users');
console.log(userStore.url);                    4
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":1,\"ch\":47},{\"line\":1,\"ch\":48}],[{\"line\":2,\"ch\":47},{\"line\":2,\"ch\":48}],[{\"line\":6,\"ch\":47},{\"line\":6,\"ch\":48}],[{\"line\":11,\"ch\":47},{\"line\":11,\"ch\":48}]]"}
!@%STYLE%@!

Here, `domain` is stored on `DataStore`; its static `url` method uses that value to build a URL. The constructor calls the method to set an instance’s URL. section 27.6

Use a static field for a value shared by objects; use an instance property when objects need different values.

  • A bicycle’s wheel count is defined on `Bicycle`, not on each bike instance or the prototype. section 27.6
  • A comet class sets a shared green stroke statically, while each comet gets its own shape on the instance. section 29.2
  • A ship class sets static shape and stroke values to determine how its sprites look. section 29.1

Static fields are syntactic sugar for assigning properties directly to the class, as in `DataStore.domain = 'https://example.com'`. They are distinct from static methods, which were introduced in ES2015; static fields were described as a proposal at the time. section 27.6

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Defines storage on the constructor rather than instances or prototype, shows assignment-style desugaring, and stops short of deeper mechanics.
Examples
Demonstrates a DataStore domain, a bicycle wheel count, and shared sprite styling contrasted with unique comet shapes.
What you can do after
Apply static fields to place shared configuration and appearance values on classes, while keeping per-object variation on instances.
How it connects
Connects static fields with classes, constructors, instance properties, prototypes, and static methods.

Also explained in

Compare how 7 books explain static field →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.