Classes: blueprints for objects
Constructors, methods, getters, inheritance with extends, and truly private fields.
Lesson 14 of 23 in JavaScript12 min1 exercise
A class bundles data and the functions that work on it. new creates an instance, and the constructor sets it up. Methods live on the prototype, so all instances share them.
class Cart {
constructor(owner) {
this.owner = owner;
this.items = [];
}
add(item) {
this.items.push(item);
return this.items.length;
}
get total() {
return this.items.length;
}
static empty() {
return new Cart("guest");
}
}
const cart = new Cart("Ada");
cart.add("pen");
cart.total; // 1 — no parentheses, it is a getter
Cart.empty().owner; // "guest"extends builds on another class. Call super(...) before using this in the child constructor.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}
new Dog("Rex").speak(); // "Rex barks"
new Dog("Rex") instanceof Animal; // trueTry it
Inheritance in action
main.js
console · output appears here
Exercises
Checked in your browser · hints and solutions included
01
Exercise
Write a Stack class
Build a Stack class with:
push(value)— add to the toppop()— remove and return the top value; throw anErrorwith the messageStack is emptywhen there is nothing to poppeek()— return the top value without removing it (undefinedwhen empty)get size()— the current number of items
Keep the storage private.
exercise.js
console · run your code or check the answer