OOP & Classes in JavaScript - Exercise 2

Use extends to create a child class that inherits from a parent class.

javascript

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.

javascript

class PremiumUser extends User {
  constructor(name, plan) {
    super(name);
    this.plan = plan;
  }
}

Define a method with the same name in the child class.

javascript

class Admin extends User {
  describe() {
    return `${this.name} has admin access`;
  }
}

Use super.methodName() inside the child method.

javascript

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.

javascript

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.

javascript

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.

javascript

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.

javascript

function printArea(shape) {
  console.log(shape.area());
}
// Circle and Rectangle can both provide area().

Composition combines small capabilities without forcing a class into a rigid inheritance hierarchy.

javascript

const canLog = object => ({
  ...object,
  log() { console.log(this.name); }
});
const user = canLog({ name: 'Ada' });

Check required values in the constructor so every instance starts in a valid state.

javascript

class Product {
  constructor(price) {
    if (price < 0) throw new Error('Price must be positive');
    this.price = price;
  }
}
All sections expanded. Activate the control to collapse all sections.