Classes and this
Classes: class and new
A template for many similar objects: data in fields, behavior in shared methods.
Why it exists
When there's one object, a { … } literal is enough. But a shop has thousands of carts, a game has dozens of characters, a page has hundreds of buttons. Copying a literal by hand means copying the methods too — and any bug in them. A class describes a kind of object once: what fields it has and what it can do. Then new stamps out as many instances as you like, each with its own data and shared methods. It's a way to keep data and the actions on it together — what's called object-oriented programming.
Where it's used
- JavaScript's own built-in types: new Map(), new Set(),
new Date(),new URL(...),new Promise(...). - Models in an app: a cart, a user, a game character, a player with a song queue.
- Custom error classes:
class ValidationError extends Error— to tell "bad email" apart from a server crash. - API clients and SDKs:
new Stripe(key),new OpenAI({ apiKey }); React class components and web components (class MyButton extends HTMLElement).
Syntax
class Name {
#private = value;
constructor(params) {
this.field = value;
}
method() { … }
get property() { return …; }
}
const obj = new Name(args);
class Child extends Name {
constructor(params) {
super(params);
}
}Examples
class Robot {
constructor(name) {
this.name = name;
this.energy = 100;
}
work(hours) {
this.energy -= hours * 10;
return this.energy;
}
}
const bolt = new Robot("Bolt");
bolt.work(3); // → 70
bolt.name; // → "Bolt"
new Robot("Nutty").energy; // → 100class Animal {
constructor(name) {
this.name = name;
}
speak() {
return this.name + " makes a sound";
}
}
class Cat extends Animal {
speak() {
return super.speak() + ": meow";
}
}
new Cat("Byte").speak(); // → "Byte makes a sound: meow"
new Animal("Rex").speak(); // → "Rex makes a sound"extends inherits, super.speak() calls the parent's methodclass Account {
#balance = 0;
deposit(sum) {
this.#balance += sum;
}
get balance() {
return "$" + this.#balance;
}
}
const acc = new Account();
acc.deposit(500);
acc.balance; // → "$500"
acc["#balance"]; // → undefined — the private field isn't visible outside# field and a getter: read like a property, computed like a methodclass ValidationError extends Error {
constructor(field) {
super("Invalid field: " + field);
this.name = "ValidationError";
this.field = field;
}
}
const err = new ValidationError("email");
err.message; // → "Invalid field: email"
err.field; // → "email"
err instanceof Error; // → trueextends in real codeResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
new Robot("Bolt") takes four steps:
- creates an empty object;
- links it to
Robot.prototype, where the class's methods live; - runs the
constructorwith this set to the new object; - returns the object.
So the fields from the constructor (this.energy = 100) are each instance's own, while the methods are written once in the prototype and shared by everyone. bolt.work(3) looks for work on bolt itself, doesn't find it and takes it from the prototype; this inside is bolt, the object before the dot.
extends builds a prototype chain: a Cat instance looks for a method first in Cat.prototype, then in Animal.prototype. super(...) in a child's constructor calls the parent's constructor — you can't use this before it. super.method() calls the parent's version.
Classes arrived in 2015 (ES6), but they aren't a new mechanism — just a convenient way to write what JavaScript could always do: constructor functions and prototypes. typeof Robot is "function". Code inside a class always runs in strict mode. # fields (2022) are truly private: outside code can't reach them at all.
Traps
How it differs from…
- Objects
{ } A
{ … }literal is for a single object (settings, a server response). A class is for when there are many objects of one kind with shared behavior.- Closure
Private state can also hide in a closure (
makeCounter). A class with#fieldsdoes the same, but its methods are shared by all instances instead of being created anew for each one.
When to pick something else
If you need plain data with no behavior, an object or an array is enough: a class for { name, price } only adds ceremony. If the "object" is a single function, let it be a function. And don't build extends chains five levels deep: they're hard to change; it's usually simpler to assemble an object from several small ones.
Practice
Lessons where this appears
- Byte's cat showTale · Chapter 11 · Map and Set
- Why not a plain object?Why? · Chapter 11 · Map and Set
- Byte's robot factoryTale · Chapter 14 · this and classes
- The assembly lineWorkshop · Chapter 14 · this and classes
- A cart classLab · Chapter 14 · this and classes
- Rusty MegabotBoss · Chapter 14 · this and classes