OOP & Classes in JavaScript - Exercise 2
Use extends to create a child class that inherits from a parent class.
class Admin extends User {
deleteAccount() {
return 'Account deleted';
}
}A derived constructor must call super() before using this so the parent constructor can initialize the instance.
class PremiumUser extends User {
constructor(name, plan) {
super(name);
this.plan = plan;
}
}Define a method with the same name in the child class.
class Admin extends User {
describe() {
return `${this.name} has admin access`;
}
}Use super.methodName() inside the child method.
class Admin extends User {
describe() {
return `${super.describe()} and is an admin`;
}
}A getter computes a value while allowing callers to use property-style syntax.
class Circle {
constructor(radius) { this.radius = radius; }
get area() { return Math.PI * this.radius ** 2; }
}
console.log(new Circle(2).area);A setter controls what happens when a property is assigned.
class Temperature {
set celsius(value) {
if (value < -273.15) throw new Error('Too cold');
this.value = value;
}
}Prefix the field name with #. It can only be accessed inside the class.
class BankAccount {
#balance = 0;
deposit(amount) { this.#balance += amount; }
get balance() { return this.#balance; }
}Different classes can provide the same method interface while implementing the behavior differently.
function printArea(shape) {
console.log(shape.area());
}
// Circle and Rectangle can both provide area().