» Quick Introduction to JavaScript » 2. Advanced » 2.3 Classes

Classes

JavaScript classes were introduced as part of ECMAScript 2015 (ES6). The ECMAScript 2015 specification, also known as ES6, brought significant enhancements to JavaScript, and one of the notable features was the introduction of class syntax for defining classes in a more structured and object-oriented manner.

Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are unique to classes.

class Person {
  // Constructor to initialize the object
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  displayInfo() {
    console.log(`Name: ${this.name}, Age: ${this.age}`);
  }
}

// Create an instance of the Person class
const person1 = new Person("Literank", 25);

person1.displayInfo();

Inheritance

class Animal {
  constructor(name) {
    this.name = name;
  }

  makeSound() {
    console.log("Generic animal sound");
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    // Call the constructor of the parent class (Animal)
    super(name);
    this.breed = breed;
  }

  // Override the makeSound method
  makeSound() {
    console.log("Woof! Woof!");
  }

  fetch() {
    console.log(`${this.name} is fetching the ball.`);
  }
}

const myDog = new Dog("Buddy", "Golden Retriever");

myDog.makeSound(); // Outputs: Woof! Woof!
myDog.fetch();     // Outputs: Buddy is fetching the ball.

Code Challenge

Create the SportsCar subcalss for the Car class.

Loading...
> code result goes here
Prev
Next