Inheritance: extends and super
A class can inherit from another to reuse and specialize its
behavior, using extends:
class Animal {
constructor(name) {
this.name = name;
}
describe() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
describe() {
return `${this.name} barks`;
}
}
If the subclass has its own constructor, it must call super(...) to
initialize the inherited part:
class Cat extends Animal {
constructor(name, color) {
super(name); // runs Animal's constructor
this.color = color;
}
}
super.method() also lets you call a method of the parent class.
Encapsulation: private fields
By default, all properties are accessible from outside. For data that should
not be touched directly, use private fields with #:
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
get balance() { // getter: read like a property
return this.#balance;
}
}
const c = new BankAccount();
c.deposit(100);
console.log(c.balance); // 100 (c.#balance would throw an error)
Getters and setters
They let you run logic when reading (get) or assigning (set) a
property, while keeping a simple syntax:
class Temperature {
#celsius = 0;
get fahrenheit() {
return this.#celsius * 9 / 5 + 32;
}
set fahrenheit(f) {
this.#celsius = (f - 32) * 5 / 9;
}
}
Examples
Inheritance with super and a getter
class Vehicle {
constructor(brand) {
this.brand = brand;
}
describe() {
return "Vehicle " + this.brand;
}
}
class Car extends Vehicle {
constructor(brand, doors) {
super(brand);
this.doors = doors;
}
describe() {
return super.describe() + " with " + this.doors + " doors";
}
}
console.log(new Car("Seat", 5).describe());