Skip to content

J100 Simple Class

Understanding the basics of class creation and inheritance in JavaScript.

In your app.js:

Task:

  1. Create a class named Car.
  2. This class should have a constructor that takes brand, model, and year as parameters and saves them as fields.
  3. Add a method named write() to this class which logs the car details to the console.
  4. Now, extend the Car class with another class named Truck.
Solution
"use strict";

// Car class
class Car {
    constructor(brand, model, year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    write() {
        console.log(`${this.brand} ${this.model} from ${this.year}`);
    }
}

// Test Car class
let car = new Car("VW", "Golf", 2022);
car.write(); // VW Golf from 2022

// Extra: Truck class that extends Car
class Truck extends Car {
    constructor(brand, model, year, totalWeight) {
        super(brand, model, year);
        this.totalWeight = totalWeight;
    }

    write() {
        console.log(`${this.brand} ${this.model} from ${this.year} which has a total weight of ${this.totalWeight}`);
    }
}

// Test Truck class
let truck = new Truck("Volve", "X1", 2000, 100000);
truck.write(); // Volve X1 from 2000 which has a total weight of 100000

This exercise introduces learners to the world of class-based object-oriented programming in JavaScript. It covers the basics of creating classes, constructors, methods, and extends the understanding to inheritance.