JSFiddle - React, Tailwind, and code Playground

by Federico

JavaScript

class Person {
  constructor(name = 'Anonymous', age = 0) {
    this.name = name;
    this.age = age;
  }
  getGreetings() {
    return `Hi, I am ${this.name}.`
  }
  getDescription() {
    return `${this.name} is ${this.age} year(s) old`
  }
}

class Student extends Person {
  constructor(name, age, major) {
    super(name, age);
    this.major = major;
  }
  hasMajor() {
    return !!this.major;
  }
  getDescription() {
    let description = super.getDescription();
    
    if (this.hasMajor()) {
      description += ` Their major is ${this.major}`;
    }
    
    return description;
  }
}

class Traveler extends Person {
  constructor(name, age, homeLocation) {
    super(name, age);
    this.homeLocation = homeLocation;
  }
  hasHomeLocation() {
    return !!this.homeLocation;
  }
  getGreetings() {
    let greetings = super.getGreetings();
    
    if (this.hasHomeLocation()) {
      greetings += `I'm visiting from ${this.homeLocation}!`;
    }
    
    return greetings;
  }
}

const me = new Traveler('Federico Taddei', 41, 'Rome');
const noone = new Traveler();

console.log(me.getGreetings());
console.log(noone.getGreetings());

console.log(me.getDescription());
console.log(noone.getDescription());