Lesson 58 of 296
Classes
What you will learn
- Class syntax: constructor, methods, fields
- Static members
- Private fields with
# - Getters and setters in classes
- Inheritance with
extendsandsuper - What classes really are underneath
- Rewriting a class with prototypes
On this page
What is a class?
A class is a template for creating objects that share the same structure and behaviour. Each object created from it is an instance.
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
greet() {
return `Hi, I am ${this.name}`;
}
}
const sam = new User("Sam", "sam@example.com");
sam.greet(); "Hi, I am Sam"| Part | Meaning |
|---|---|
class User | Defines the class. Class names use PascalCase (capital first letter). |
constructor | Runs automatically when you use new. Sets up the instance. |
this.name = name | Creates a property on the new instance |
greet() | A method, shared by all instances via the prototype |
new User(...) | Creates an instance |
Class fields
Properties can be declared directly in the class body:
class Cart {
items = [];
discount = 0;
add(item) {
this.items.push(item);
}
}Each instance gets its own items array.
Private fields
A # before a name makes it truly private: it can only be used inside the class.
class BankAccount {
#balance = 0;
deposit(amountPence) {
if (amountPence <= 0) throw new Error("Amount must be positive");
this.#balance += amountPence;
}
getBalance() {
return this.#balance;
}
}
const acc = new BankAccount();
acc.deposit(5000);
acc.getBalance(); 5000
acc.#balance; SyntaxErrorThis is called encapsulation: hiding internal data and only allowing changes through controlled methods. Private methods (#validate()) also exist.
Static members
Static properties and methods belong to the class itself, not to instances.
class Temperature {
static fromFahrenheit(f) {
return new Temperature((f - 32) * 5 / 9);
}
constructor(celsius) {
this.celsius = celsius;
}
}
const t = Temperature.fromFahrenheit(212);
t.celsius; 100Use static for helpers and "factory" methods that create instances. Math.max and Array.isArray are static methods of built-in classes.
Getters and setters
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
const r = new Rectangle(3, 4);
r.area; 12 (no brackets: it looks like a property)Setters (set name(value) {...}) run when a property is assigned. Lesson 74 covers both.
Inheritance: extends and super
A class can extend another class and inherit everything from it.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
return `${this.name} barks`;
}
describe() {
return `${super.speak()} (a ${this.breed})`;
}
}
const rex = new Dog("Rex", "Labrador");
rex.speak(); "Rex barks"
rex.describe(); "Rex makes a sound (a Labrador)"
rex instanceof Animal trueextendssets up inheritance:Dog.prototype's prototype isAnimal.prototype.super(name)calls the parent's constructor. In a child class, you must callsuper()before usingthis.- Defining
speakinDogoverrides the parent's version. super.speak()calls the parent's version.
Classes are built on prototypes
Classes do not add a new kind of inheritance. They are a clearer way to write what Lesson 57 did with constructor functions. This is often described as syntactic sugar.
typeof User "function"
Object.getPrototypeOf(sam) === User.prototype trueThe same class written with prototypes
function User(name, email) {
this.name = name;
this.email = email;
}
User.prototype.greet = function () {
return `Hi, I am ${this.name}`;
};Differences classes add:
- A class must be called with
new. CallingUser()without it throws an error. - Class code always runs in strict mode.
- Class declarations are in the TDZ until their line (Lesson 52).
- Private
#fields have no exact prototype equivalent.
Composition over inheritance
Deep inheritance chains (Animal > Mammal > Dog > ServiceDog > ...) become rigid and hard to change. Many teams prefer composition: building objects from smaller pieces of behaviour rather than long family trees. Part 21 covers this. In modern React code, classes are rare; functions and hooks are used instead. Classes are common in NestJS (Part 16) and in back end code.
Common mistakes
- Forgetting
new. - Using
thisbeforesuper()in a child constructor. - Arrow function methods vs normal methods: normal methods are shared on the prototype; arrow function fields are created per instance (they fix
this, but cost more memory). - Building deep inheritance trees.
How to say it in an interview
"A class is a template for objects. The constructor runs with new to set up instance properties, and methods are placed on the prototype so instances share them. I use private # fields for encapsulation, static methods for factory and utility functions, and extends with super for inheritance. Classes are syntactic sugar over JavaScript's prototype system: typeof a class is 'function', and instances link to Class.prototype. I keep inheritance shallow and prefer composition."
Key words
| Word | Meaning |
|---|---|
| Class | A template for creating objects |
| Instance | An object created from a class |
| Constructor | The method that sets up a new instance |
| Field | A property declared in the class body |
| Private field | A # property only usable inside the class |
| Static | Belongs to the class itself, not instances |
| extends / super | Inherit from a parent class / call the parent |
| Override | Replace a parent's method in a child class |
| Encapsulation | Hiding internal data behind methods |
| Syntactic sugar | Nicer syntax for something that already exists |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.