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






