Classes, inheritance and prototypes
Create object blueprints with classes, extend them, protect data with private fields, and understand the prototype chain.
In this lesson you will
- Write classes with constructors and methods
- Use getters, setters, static and private members
- Extend classes with extends and super
- Explain the prototype chain
About 22 minutes
Blueprints for objects
A builder does not design every house from scratch. She has a blueprint, and from one blueprint she can build twenty houses, each with its own address and colour, but the same structure. In JavaScript, a class is a blueprint for objects. Define it once, then create as many objects (called instances) as you like, all sharing the same abilities.
Your first class
class User {
constructor(name, email) {
this.name = name;
this.email = email;
this.active = true;
}
greet() {
return `Hi, I am ${this.name}`;
}
deactivate() {
this.active = false;
}
}
const sara = new User("Sara", "sara@mail.com");
const ali = new User("Ali", "ali@mail.com");
console.log(sara.greet());
ali.deactivate();
console.log(ali.active, sara.active);
class Userdeclares the blueprint. Class names start with a capital letter by convention.constructorruns automatically when you writenew User(...). It sets up the new object’s data usingthis.- Methods are written without the
functionkeyword and shared by every instance. newbuilds an instance.
Create a class Rectangle with width and height, and methods area() and perimeter(). Make two rectangles and print their area.
// write class Rectangle
constructor(w, h) { this.width = w; this.height = h; } area() { return this.width * this.height; }
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() { return this.width * this.height; }
perimeter() { return 2 * (this.width + this.height); }
}
const a = new Rectangle(4, 5);
const b = new Rectangle(10, 2);
console.log(a.area(), a.perimeter());
console.log(b.area(), b.perimeter());
Getters, setters and static members
class Temperature {
constructor(celsius) { this.celsius = celsius; }
get fahrenheit() { // read like a property
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(f) { // assign like a property
this.celsius = (f - 32) * 5 / 9;
}
static fromFahrenheit(f) { // belongs to the class, not instances
const t = new Temperature(0);
t.fahrenheit = f;
return t;
}
}
const t = new Temperature(100);
console.log(t.fahrenheit); // 212
console.log(Temperature.fromFahrenheit(32).celsius); // 0
A getter looks like a property but runs code. A setter runs code when you assign. A static method belongs to the class itself and is called on the class name, which is handy for helper functions and alternative ways of creating objects.
Private fields
class Account {
#balance = 0; // truly private
deposit(amount) {
if (amount <= 0) throw new Error("Amount must be positive");
this.#balance += amount;
}
get balance() { return this.#balance; }
}
const acc = new Account();
acc.deposit(500);
console.log(acc.balance); // 500
// console.log(acc.#balance); // SyntaxError: private
Fields starting with # can only be touched from inside the class. That protects important data (like a balance) so other code must go through your checked methods, such as deposit.
Inheritance: extending a class
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // run the parent's constructor first
this.breed = breed;
}
speak() { // override
return `${this.name} barks`;
}
fetch() { return `${this.name} fetches the ball`; }
}
const d = new Dog("Rex", "Labrador");
console.log(d.speak()); // Rex barks
console.log(d instanceof Animal); // true
console.log(Object.getPrototypeOf(Dog) === Animal); // true
extends makes Dog a specialised Animal: it automatically has everything Animal has, plus its own extras. super(...) calls the parent’s constructor and is required before you use this. Defining a method with the same name overrides the parent’s version.
Create class Shape with a describe() method returning ‘A shape’, then class Circle extends Shape that overrides describe() to say ‘A circle with radius r’. Print both.
class Shape {
describe() { return 'A shape'; }
}
// write Circle
class Circle extends Shape { constructor(r) { super(); this.r = r; } describe() { return `A circle with radius ${this.r}`; } }
class Shape {
describe() { return 'A shape'; }
}
class Circle extends Shape {
constructor(r) {
super();
this.r = r;
}
describe() { return `A circle with radius ${this.r}`; }
}
console.log(new Shape().describe());
console.log(new Circle(3).describe());
What is really going on: prototypes
Classes are a friendly coat of paint over a mechanism called prototypes. Every object has a hidden link to another object, its prototype. When you ask for a property or method, JavaScript looks on the object, then on its prototype, then on that one’s prototype, and so on up a prototype chain until it finds it or reaches the end. Methods live on the prototype once, and every instance shares them, which saves memory.
class Pet { speak() { return "..."; } }
const p = new Pet();
console.log(Object.getPrototypeOf(p) === Pet.prototype); // true
console.log(p.hasOwnProperty("speak")); // false: lives on the prototype
console.log("speak" in p); // true
console.log(typeof Pet); // "function": classes are functions
This is also why arrays have map and strings have toUpperCase: those methods live on Array.prototype and String.prototype.
When to use classes
- You need many objects of the same shape with behaviour, such as users, products, game characters.
- You want to protect state with private fields.
- You work with a library or framework that expects classes.
When you need just one object, a plain object literal is simpler. When you need only functions, plain functions are fine. JavaScript lets you choose the simplest tool for the job.
Forgetting new: const u = User("Sara") throws an error for classes. Another classic: using this before calling super() inside a subclass constructor, which is also an error.
Chains of three or four parent classes become hard to follow. Prefer small classes that use each other (a Car has an Engine) over long inheritance trees (a Car is a Vehicle is a Machine).
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does new User() do?
- Deletes a user
- Creates a new instance and runs the constructor
- Defines a class
- Copies an array
new builds an instance.
What is super(name) for?
- Making a variable global
- Deleting the parent
- Creating a getter
- Calling the parent class constructor
It runs the parent’s constructor.
What does a # before a field mean?
- It is a comment
- It is private to the class
- It is static
- It is a number
Private fields cannot be accessed from outside.
What is a static method?
- A method that never changes
- A private method
- A getter
- A method called on the class itself
Static members belong to the class.
Where do class methods live?
- On the prototype, shared by all instances
- Copied into every instance
- In the DOM
- In localStorage
Prototype methods are shared, which saves memory.
Summary
- A class is a blueprint; new creates instances.
- extends and super build specialised classes.
- # fields are truly private.
- Classes are built on prototypes.
Questions
Are JavaScript classes the same as in Java?
They look similar, but they are built on prototypes underneath, and objects can be created without classes.
When should I not use a class?
When a plain object or a few functions do the job. Do not add structure you do not need.
What does instanceof check?
Whether an object was created by a class or one of its subclasses.
