Classes and OOP · Lesson 27 of 45
Classes
A template for making many objects of the same shape.
9 minutes3 games
A class is a blueprint. Instead of hand-writing an object for every student, you define the shape once and create copies (instances) with new. The constructor runs when an instance is created and sets up its data.
JavaScript
class Student {
constructor(name, level = 1) {
this.name = name
this.level = level
this.xp = 0
}
earn(points) {
this.xp += points
if (this.xp >= 100) {
this.level++
this.xp -= 100
}
}
get title() {
return `${this.name} (level ${this.level})`
}
}
const a = new Student("Laila")
const b = new Student("Karim", 3)
a.earn(130)
console.log(a.title, a.xp)
console.log(b.title)- class Student
- a = new Student("Laila")
- name: "Laila"
- level: 2
- b = new Student("Karim", 3)
- name: "Karim"
- level: 3
- a = new Student("Laila")
One blueprint, many instances, each with its own data.
Private fields #
JavaScript
class Wallet {
#balance = 0 // private: not reachable from outside
deposit(amount) {
if (amount <= 0) throw new Error("Amount must be positive")
this.#balance += amount
}
get balance() {
return this.#balance
}
}
const w = new Wallet()
w.deposit(200)
console.log(w.balance)
console.log(w["#balance"]) // undefinedWhat's the output?
class Counter {
constructor() {
this.n = 0
}
inc() {
this.n++
return this
}
}
console.log(new Counter().inc().inc().inc().n)What will this code print?
Complete the code
Complete the class and create an instance.
class Book { (title) { this.title = title } } const b = Book("JS 101")
Exercise
Make a Rectangle class with width, height and an area() method. Print new Rectangle(5, 4).area() (20).
Expected output: 20
JavaScript
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.