Classes and prototypes
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- Final project: a post explorer with modules and fetch
Making many similar objects
If you need one user object, an object literal is fine. If you need hundreds of users that all have the same shape and behaviour, you want a blueprint. In JavaScript, that is a class.
Class syntax
class BankAccount {
constructor(owner, balance = 0) {
this.owner = owner;
this.balance = balance;
}
deposit(amount) {
if (amount <= 0) throw new Error("Amount must be positive");
this.balance += amount;
return this;
}
withdraw(amount) {
if (amount > this.balance) throw new Error("Insufficient funds");
this.balance -= amount;
return this;
}
describe() {
return `${this.owner}: Rs. ${this.balance}`;
}
}
const account = new BankAccount("Ali", 1000);
account.deposit(500).withdraw(200);
console.log(account.describe()); // Ali: Rs. 1300
constructor runs when you write new BankAccount(...). It sets up the properties of the new object. The methods are shared by all instances. Because deposit and withdraw return this, you can chain the calls.
Calling a class without new throws an error. That is a good thing, since it prevents a silent mistake.
Getters, setters and static members
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
}
static fromFahrenheit(value) {
return new Temperature((value - 32) * 5 / 9);
}
}
const t = new Temperature(100);
console.log(t.fahrenheit); // 212
t.fahrenheit = 32;
console.log(t.celsius); // 0
console.log(Temperature.fromFahrenheit(212).celsius); // 100
A getter looks like a property but runs code. A static method belongs to the class itself and is called on it, not on an instance. It is often used for alternative ways to create objects.
Private fields
A name starting with # is private. Code outside the class cannot read or write it.
class Counter {
#count = 0;
increment() {
this.#count++;
return this.#count;
}
get value() {
return this.#count;
}
}
const c = new Counter();
c.increment();
c.increment();
console.log(c.value); // 2
// console.log(c.#count); // SyntaxError
Use private fields to protect state that should only change through your methods. This is real privacy, enforced by the language. It is different from the old habit of starting names with an underscore, which only asks other people politely not to touch them.
Inheritance
A class can extend another to reuse and specialise its behaviour.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // must come before using this
this.breed = breed;
}
speak() {
return `${super.speak()}: woof`;
}
}
const d = new Dog("Rex", "Labrador");
console.log(d.speak()); // Rex makes a sound: woof
console.log(d instanceof Animal); // true
super(name) calls the parent constructor. In a child class you must call it before you touch this. super.speak() calls the parent version of a method.
A word of advice from experience. Inheritance is easy to overuse. Deep chains of classes become rigid, and a change in the parent breaks children in surprising ways. Often a plain function, or an object that holds another object (composition), is simpler. I reach for extends only when there is a true "is a" relationship and it goes one level deep.
Prototypes: what is under the hood
JavaScript classes are a friendlier syntax over prototypes. Every object has a hidden link to another object, its prototype. When you read a property, JavaScript looks at the object first. If it is not there, it follows the link to the prototype, then to that object's prototype, and so on, until it reaches the end of the chain. This is the prototype chain.
const d = new Dog("Rex", "Lab");
console.log(Object.getPrototypeOf(d) === Dog.prototype); // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
console.log(d.hasOwnProperty("name")); // true, set on the instance
console.log(d.hasOwnProperty("speak")); // false, found on the prototype
Methods live once on Dog.prototype, not on every instance. That saves memory, and it is why changing a class method affects all existing objects. You do not need to touch prototypes directly in everyday code. Knowing the model helps you understand error messages and library code.
Common mistakes
- **Forgetting
new.** CallingBankAccount("Ali")throws a TypeError. - **Using
thisbeforesuper().** You get a ReferenceError in a subclass constructor. - Passing a method as a callback.
button.addEventListener("click", account.describe)losesthis. The next lesson covers this problem. - Putting commas between class methods. Class bodies do not use commas.
- Deep inheritance. Prefer small classes that use other objects.
Try it yourself
- Create a
Rectangleclass withwidth,heightand anarea()method. Add aSquareclass that extends it. - Add a private field
#historytoBankAccountthat records each transaction, and a method that returns a copy of the history. - Write a static method
Temperature.compare(a, b)that returns the warmer one. - Log
Object.getPrototypeOf(account)for the account object and explain what you see.
class BankAccount {
constructor(owner, balance = 0) {
this.owner = owner;
this.balance = balance;
}
deposit(amount) {
if (amount <= 0) throw new Error("Amount must be positive");
this.balance += amount;
return this;
}
withdraw(amount) {
if (amount > this.balance) throw new Error("Insufficient funds");
this.balance -= amount;
return this;
}
describe() {
return `${this.owner}: Rs. ${this.balance}`;
}
}
const account = new BankAccount("Ali", 1000);
account.deposit(500).withdraw(200);
console.log(account.describe()); // Ali: Rs. 1300
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account