Class Static
static members belong to the class itself, not to instances. They're useful for factories, constants, and utility methods that don't need an instance to work.
Static methods, fields, and blocks
JS
class User {
// Static field — shared by everyone
static count = 0;
// Static block — runs once when the class is defined
static {
User.MAX_NAME_LEN = 60;
}
constructor(name) {
this.name = name;
User.count++;
}
// Static factory
static fromJSON(text) {
const { name } = JSON.parse(text);
return new User(name);
}
// Static utility
static isValidName(name) {
return typeof name === "string" && name.length < User.MAX_NAME_LEN;
}
}
new User("Ada");
new User("Grace");
User.count; // 2
User.fromJSON('{"name":"Linus"}'); // User { name: "Linus" }
User.isValidName(""); // true (technically) — adjust as needed
How to call
- Always call on the class:
User.fromJSON(…). - Never on an instance:
u.fromJSONisundefined. - Inside another static, refer to siblings via the class name or
this(the class itself).
When static earns its keep
| Pattern | Example |
|---|---|
| Factory | Date.now(), Array.from(), Promise.resolve() |
| Type test | Array.isArray(x), Number.isFinite(x) |
| Constant grouping | Math.PI, Number.MAX_SAFE_INTEGER |
| Instance counter | Shared registries or pools. |
Tip: If a method doesn't use
this, it probably wants to be static — or just a plain module-level function.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from Class Static!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Mark this factory as belonging to the class itself.
class User {
fromJSON(text) { return new User(JSON.parse(text).name); } }
Six letters.
Discussion
Loading…