</> Code Corner

JavaScript · JS Functions & Objects · Lesson 42

JS Classes

Templates for objects: constructor, methods and inheritance.

A JavaScript class is a template for creating objects. Use the keyword class and always add a constructor() method.

Example

<p id="demo"></p>
<script>
class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age(currentYear) {
    return currentYear - this.year;
  }
}
class ElectricCar extends Car {
  constructor(name, year, range) {
    super(name, year);
    this.range = range;
  }
  describe() {
    return this.name + " can drive " + this.range + " km";
  }
}
const myCar = new Car("Ford", 2014);
const tesla = new ElectricCar("Tesla", 2022, 500);
document.getElementById("demo").innerHTML =
  "My car is " + myCar.age(2026) + " years old.<br>" + tesla.describe();
</script>
  • new creates an object and calls the constructor
  • extends creates a child class that inherits all methods
  • super() calls the parent constructor

Keep reading “JS Classes”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋