Lesson 6 of 18 · 0 of 2 exercises solved
Classes & Modules
You will learn how to define classes and split code into . Classes group data with the that act on it, and modules keep larger programs organised.
class Animal {
#name; // private field (# prefix)
constructor(name, sound) {
this.#name = name;
this.sound = sound;
}
speak() {
return `${this.#name} says ${this.sound}`;
}
get name() { return this.#name; } // getter
}
class Dog extends Animal {
constructor(name) {
super(name, "Woof"); // call parent constructor
this.tricks = [];
}
learn(trick) {
this.tricks.push(trick);
return this; // enables chaining
}
showTricks() {
return `${this.name} knows: ${this.tricks.join(", ")}`;
}
}
const dog = new Dog("Rex");
dog.learn("sit").learn("shake").learn("roll over");
console.log(dog.speak()); // Rex says Woof
console.log(dog.showTricks()); // Rex knows: sit, shake, roll over// ES Modules — one file, one module
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
export default function square(x) { return x * x; }
// In another file:
// import square, { PI, add } from './math.js';
// console.log(square(4)); // 16
// console.log(add(2, 3)); // 5
// CommonJS (Node.js older style)
// module.exports = { add, multiply };
// const { add } = require('./math');
// Dynamic import (lazy loading)
// const module = await import('./heavy-module.js');Practice
Build a Counter with increment() and decrement() , a value getter, and a constructor that accepts an optional starting value (default 0). Methods should return this so calls can be chained.
Exercise
3 checksA chainable Counter
class Counter {
constructor(start) {
}
}
const c = new Counter()
c.increment().increment().decrement()
console.log(c.value)
Press Run to try your code, then Check answer to grade it.Shape is a base class with an area() that returns 0 and a describe() using it. Write Circle(radius) and Square(side) subclasses that override area(). Use super in the constructors.
Exercise
4 checksInheritance
class Shape {
constructor(name) {
this.name = name
}
area() {
return 0
}
describe() {
return `${this.name} with area ${this.area().toFixed(2)}`
}
}
// class Circle extends Shape ...
// class Square extends Shape ...
console.log(new Circle(1).describe())
console.log(new Square(3).describe())
Press Run to try your code, then Check answer to grade it.Check yourself
What is a JavaScript class, underneath?
Finished reading?2 exercises still open. You can come back to them later.
Tip: use the ← and → keys to move between lessons.